我在使用kivy库方面还是个新手。
我有一个app.py文件和一个app.kv文件,我的问题是我不能在按下按钮时调用函数。
app.py:
import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
class Launch(BoxLayout):
def __init__(self, **kwargs):
super(Launch, self).__init__(**kwargs)
def say_hello(self):
print "hello"
class App(App):
def build(self):
return Launch()
if __name__ == '__main__':
App().run()app.kv:
#:kivy 1.9.1
<Launch>:
BoxLayout:
Button:
size:(80,80)
size_hint:(None,None)
text:"Click me"
on_press: say_hello发布于 2017-09-22 07:31:30
模式:.kv
它非常简单,say_hello属于Launch类,所以为了在.kv文件中使用它,您必须编写root.say_hello。请注意,say_hello是您想要执行的函数,因此您不必忘记() -> root.say_hello()。
此外,如果say_hello在App类中,您应该使用App.say_hello(),因为它属于应用程序。(注意:即使你的应用程序类是class MyFantasicApp(App):,它也总是App.say_hello()或app.say_hello(),对不起,我不记得了)。
#:kivy 1.9.1
<Launch>:
BoxLayout:
Button:
size:(80,80)
size_hint:(None,None)
text:"Click me"
on_press: root.say_hello()模式:.py
您可以对函数执行bind操作。
from kivy.uix.button import Button # You would need futhermore this
class Launch(BoxLayout):
def __init__(self, **kwargs):
super(Launch, self).__init__(**kwargs)
mybutton = Button(
text = 'Click me',
size = (80,80),
size_hint = (None,None)
)
mybutton.bind(on_press = self.say_hello) # Note: here say_hello doesn't have brackets.
Launch.add_widget(mybutton)
def say_hello(self):
print "hello"为什么使用bind?抱歉,我不知道。但是你可以在the kivy guide中使用它。
https://stackoverflow.com/questions/46351997
复制相似问题