如何在按钮上制作图像 "float"?
How to make an image "float" over the buttons?
我开始学习 Kivy。
下面的代码生成一个 10x10 的按钮网格:
from kivy.uix.gridlayout import GridLayout
from kivy.app import App
from kivy.uix.button import Button
class MyApp(App):
def build(self):
layout = GridLayout(cols=10)
for i in range (1, 101):
layout.add_widget(Button(text=str(i)))
return layout
MyApp().run()
现在,我想将 png 图像添加到独立层,该层独立地随机 "wander" 在这些按钮上。
然后用户应该像在游戏中一样单击图像所在的按钮。
也就是说,图片不应该是可点击的,只会在按钮上方显示,同时,按钮应该完美响应,就好像它们上面没有图片一样。
如何做到这一点?
您可以使用 Rectangle
在 GridLayout
的 Canvas
中绘制图像。位置可以使用 Clock_schedule_interval()
更新。像这样:
from kivy.clock import Clock
from kivy.graphics.context_instructions import Color
from kivy.graphics.vertex_instructions import Rectangle
from kivy.uix.gridlayout import GridLayout
from kivy.app import App
from kivy.uix.button import Button
class MyApp(App):
def build(self):
layout = GridLayout(cols=10)
with layout.canvas.after:
Color(1,1,1,0.5) # if you want to see through the image
self.bg = Rectangle(source='KQxab.png') # source is the image
for i in range (1, 101):
layout.add_widget(Button(text=str(i)))
Clock.schedule_interval(self.update_bg, 1.0/24.0) # schedule the image movement
return layout
def update_bg(self, dt):
self.bg.pos = (self.bg.pos[0] + 1, self.bg.pos[1] + 1)
MyApp().run()
此代码只是使图像沿直线移动,但您可以对其进行改进。
我开始学习 Kivy。 下面的代码生成一个 10x10 的按钮网格:
from kivy.uix.gridlayout import GridLayout
from kivy.app import App
from kivy.uix.button import Button
class MyApp(App):
def build(self):
layout = GridLayout(cols=10)
for i in range (1, 101):
layout.add_widget(Button(text=str(i)))
return layout
MyApp().run()
现在,我想将 png 图像添加到独立层,该层独立地随机 "wander" 在这些按钮上。
然后用户应该像在游戏中一样单击图像所在的按钮。
也就是说,图片不应该是可点击的,只会在按钮上方显示,同时,按钮应该完美响应,就好像它们上面没有图片一样。 如何做到这一点?
您可以使用 Rectangle
在 GridLayout
的 Canvas
中绘制图像。位置可以使用 Clock_schedule_interval()
更新。像这样:
from kivy.clock import Clock
from kivy.graphics.context_instructions import Color
from kivy.graphics.vertex_instructions import Rectangle
from kivy.uix.gridlayout import GridLayout
from kivy.app import App
from kivy.uix.button import Button
class MyApp(App):
def build(self):
layout = GridLayout(cols=10)
with layout.canvas.after:
Color(1,1,1,0.5) # if you want to see through the image
self.bg = Rectangle(source='KQxab.png') # source is the image
for i in range (1, 101):
layout.add_widget(Button(text=str(i)))
Clock.schedule_interval(self.update_bg, 1.0/24.0) # schedule the image movement
return layout
def update_bg(self, dt):
self.bg.pos = (self.bg.pos[0] + 1, self.bg.pos[1] + 1)
MyApp().run()
此代码只是使图像沿直线移动,但您可以对其进行改进。