我试图让按钮调用一个函数,在kivy文件中,我可以在括号中有*args。如何让函数在python文件中工作?
main.py
from kivy.config import Config
Config.set('input', 'mouse', 'mouse,disable_multitouch')
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.uix.bubble import Bubble
class MainWidget(FloatLayout):
clicked = False
def __init__(self, **kwargs):
b = Button(text="A")
b.bind(self.onpressed)
def onpressed(self, widget, touch):
if touch.button == 'left':
print("LEFT")
if self.clicked:
self.remove_widget(self.ccp)
self.clicked = False
elif touch.button == 'right':
print("RIGHT")
if self.clicked:
self.remove_widget(self.ccp)
self.ccp = CutCopyPaste()
self.add_widget(self.ccp)
self.clicked = True
class CutCopyPaste(Bubble):
pass
class RightClickApp(App):
pass
if __name__ == "__main__":
RightClickApp().run()
rightclick.kv
MainWidget:
<MainWidget>:
#Button:
# text: "A"
# on_touch_down: root.onpressed(*args)
<CutCopyPaste>:
size_hint: (None, None)
size: (160, 160)
pos_hint: {'center_x': .5, 'y': .6}
BubbleButton:
text: 'Cut'
BubbleButton:
text: 'Copy'
BubbleButton:
text: 'Paste'
我找到的所有方法都不起作用。请帮助。
如果您希望将Button
实例和touch
对象传递给您的onpressed()
方法,那么将其绑定到提供这些参数的on_touch_down
。这样的:
def __init__(self, **kwargs):
super().__init__(**kwargs) # added missing call
b = Button(text="A")
b.bind(on_touch_down = self.onpressed)
self.add_widget(b) # added
此外,无论何时重写super()
__init__()
方法,都必须调用它。您的代码没有将Button
添加到MainWidget
。
正确的绑定语法是:
widget_instance.bind(widget_kvprop_or_event = callback_method_or_function)
这里,你可以这样做,
def __init__(self, **kwargs):
super().__init__(**kwargs)
b = Button(text="A")
# Bind the event 'on_touch_down' to a method 'onpressed'.
b.bind(on_touch_down = self.onpressed)
# Don't forget to add the widget.
self.add_widget(b)