我如何检测游戏网格的儿童小部件中的触摸位置?当我想要调用子方法mark_label()时。谢谢。
class GameGrid(GridLayout):
def on_touch_move(self, touch):
#wich label is collision
print(str(touch.pos))
class StartScreen(Screen):
level = Level(mode, 1)
def __init__(self,**kwargs):
super().__init__(**kwargs)
self.create_level()
def create_level(self):
self.ids.game_grid.clear_widgets()
labels = self.level.get_letters_label()
for f in range(len(labels)):
self.ids.game_grid.add_widget(labels[f])
答案 0 :(得分:0)
使用self.collide_points()
方法检查触摸与感兴趣的小部件的碰撞。
类CreateLabel(Label):
def on_touch_down(self, touch):
if self.collide_point(*touch.pos):
# TODO
# call method mark_label()
if touch.button == "right":
print("Right mouse clicked on {}".format(self.text))
elif touch.button == "left":
print("Left mouse clicked on {}".format(self.text))
else:
print(self.id)
return True
return super(CreateLabel, self).on_touch_down(touch)
Programming Guide » Events and Properties » Dispatching a Property event
如果触摸属于我们的小部件内部,我们会更改其值 按下touch.pos并返回True,表示我们已经消耗掉了 触摸,不希望它进一步传播。
...
最后, 如果触摸落在我们的小部件之外,我们称之为原始事件 使用super(...)并返回结果。这允许触摸事件 正常情况下继续传播。
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
class CreateLabel(Label):
def on_touch_down(self, touch):
if self.collide_point(*touch.pos):
if touch.button == "right":
print("Right mouse clicked on {}".format(self.text))
elif touch.button == "left":
print("Left mouse clicked on {}".format(self.text))
else:
print(self.id)
return True
return super(CreateLabel, self).on_touch_down(touch)
class RootWidget(GridLayout):
def __init__(self, **kwargs):
super(RootWidget, self).__init__(**kwargs)
self.build_board()
def build_board(self):
# make 9 label in a grid
for i in range(0, 9):
label = CreateLabel(id=str(i), text="Label {}".format(i))
self.add_widget(label)
class TestApp(App):
def build(self):
return RootWidget()
if __name__ == '__main__':
TestApp().run()
#:kivy 1.10.0
<CreateLabel>:
canvas.before:
Color:
rgba: 0, 1, 1, 0.5 # 50% blue
Rectangle:
size: self.size
pos: self.pos
font_size: 30
on_touch_down: self.on_touch_down
<RootWidget>:
rows: 3
cols: 3
row_force_default: True
row_default_height: 150
col_force_default: True
col_default_width: 150
padding: [10]
spacing: [10]