在函数外引用函数的正确方法
绘制小部件。
你也可以define on_press() outside the kv file:
from kivy.uix.button import Button
from kivy.app import App
def dostuff(x):
print("x is %s" % x)
class MyButton(Button):
def on_press(self):
dostuff(22)
class MyApp(App):
def build(self):
return MyButton()
MyApp().run()
我的.kv:
<MyButton>:
text: "Press Me"
或者,on_press() inside the kv file:
我的.kv:
<MyButton>:
text: "Press Me"
on_press: self.dostuff(10, 20) #Look in MyButton class for dostuff()
...
...
class MyButton(Button):
def dostuff(self, *args):
print(args)
...
...
我已经尝试过 root.dostuff parent...self...MyApp...App。
root 和 app 在 kv 文件中的工作方式如下:
我的.kv:
<MyWidget>: #This class is the 'root' of the following widget hierarchy:
Button:
text: "Press Me"
on_press: root.dostuff(20, 'hello') #Look in the MyWidget class for dostuff()
size: root.size #fill MyWidget with the Button
from kivy.uix.widget import Widget
from kivy.app import App
class MyWidget(Widget):
def dostuff(self, *args):
print(args)
class MyApp(App):
def build(self):
return MyWidget()
MyApp().run()
或者,您可以put the function inside the App class:
我的.kv:
<MyButton>:
text: "Press Me"
on_press: app.dostuff('hello', 22)
from kivy.app import App
from kivy.uix.button import Button
class MyButton(Button):
pass
class MyApp(App):
def dostuff(self, *args):
print(args)
def build(self):
return MyButton()
MyApp().run()
我可以将函数放入 Widgets 类,但这会破坏其他
东西……
好吧,不要让函数这样做。