问题描述
我有此代码,但我不知道如何冲突Label:标签和Buttons。 这是代码:
def _on_keyboard_down(self,keyboard,keycode,text,modifiers):
if keycode[1] == 'z' or keycode[1] == 'up':
self.pY += .1
for wid in self.walk():
if isinstance(wid,Button):
if Tag.collide_widget(wid):
因此,我在主类中行走(),如果它是一个Button,则使用collide_widget。想想我尝试将什么作为该函数的args,似乎没有任何作用。
这里是完整代码:** Mainfile **
from kivy.app import App
from kivy.config import Config
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import NumericProperty
from kivy.core.window import Window
from kivy.uix.label import Label
from kivy.uix.button import Button
Window.size = (900,600)
Config.set('graphics','resizable',True)
class Tag(Label):
pass
class MainWindow(FloatLayout):
pY = NumericProperty(.6)
pX = NumericProperty(.6)
def __init__(self,**kwargs):
super(MainWindow,self).__init__(**kwargs)
self._keyboard = Window.request_keyboard(self._keyboard_closed,self)
self._keyboard.bind(on_key_down=self._on_keyboard_down)
def _keyboard_closed(self):
self._keyboard.unbind(on_key_down=self._on_keyboard_down)
self._keyboard = None
def _on_keyboard_down(self,Button):
if Tag.collide_widget(Tag,wid):
self.pY -= .2
elif keycode[1] == 's' or keycode[1] == 'down':
self.pY -= .1
elif keycode[1] == 'q' or keycode[1] == 'left':
self.pX -= .1
elif keycode[1] == 'd' or keycode[1] == 'right':
self.pX += .1
elif keycode[1] == 'o':
return 0
return True
class FenetreApp(App):
def build(self):
return MainWindow()
FenetreApp().run()
Fenetre.kv文件:
<Button>:
size_hint: 0.1,0.1
background_color: 0.1,0.5,0.6,1
<Tag@Label>:
size_hint: 0.1,0.1
background_color: 1,1
canvas.before:
Color:
rgb: 0.1,0
Rectangle:
pos: self.pos
size: self.size
<MainWindow@FloatLayout>:
Button:
text: "Up"
pos_hint: {"x":0.8,"top":1}
on_press: self.parent.pY= self.parent.pY +0.1
Button:
text: "Down"
pos_hint: {"x":0.8,"top":0.8}
on_press: self.parent.pY= self.parent.pY -0.1
Button:
text: "Left"
pos_hint: {"x":0.7,"top":0.9}
on_press: self.parent.pX = self.parent.pX -0.1
Button:
text: "Right"
pos_hint: {"x":0.9,"top":0.9}
on_press: self.parent.pX = self.parent.pX +0.1
Tag:
name: "L1"
text: "move"
pos_hint: {"x":self.parent.pX,"top":self.parent.pY}
解决方法
因此,我找到了解决问题的方法: 向小部件添加ID:
Tag:
id: Tag_Layout
name: "L1"
text: "move"
pos_hint: {"x":self.parent.pX,"top":self.parent.pY}
然后通过ID访问对象:
for wid in self.walk():
if isinstance(wid,Button):
if self.ids.Tag_Layout.collide_widget(wid):
self.pY -= .2
,
if Tag.collide_widget(Tag,wid):
这没有意义,Tag
是类定义本身,它是Python代码中的抽象,与您的应用程序中的任何特定元素无关。您需要为您的应用中此类的特定实例调用collide_widget
。