問題描述
我對使用 kivy 庫很陌生.
i'm pretty new at using kivy library.
我有一個 app.py 文件和一個 app.kv 文件,我的問題是我無法在按下按鈕時調用函數.
I have an app.py file and an app.kv file , my problem is that I can't call a function on button press.
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
推薦答案
Mode:.kv
很簡單,say_hello
屬于 Launch
類,所以要在 .kv
文件中使用它,你必須編寫 <代碼>root.say_hello.請注意,say_hello
是您要執行的函數,因此您不必忘記 ()
---> root.say_hello()代碼>.
Mode:.kv
It's very simple, say_hello
belongs to the Launch
class so in order to use it in your .kv
file you have to write root.say_hello
. Note that say_hello
is a function that you want to execute so you don't have to forget the ()
---> root.say_hello()
.
另外,如果 say_hello
在 App
類中,您應該使用 App.say_hello()
因為它屬于應用程序.(注意:即使你的 App 類是 class MyFantasicApp(App):
它總是 App.say_hello()
或 app.say_hello()
我不記得了,抱歉).
Also, if say_hello
were in App
class you should use App.say_hello()
because it belongs to the app. (Note: even if your App class were class MyFantasicApp(App):
it would always be App.say_hello()
or app.say_hello()
I don't remember, sorry).
#:kivy 1.9.1
<Launch>:
BoxLayout:
Button:
size:(80,80)
size_hint:(None,None)
text:"Click me"
on_press: root.say_hello()
模式:.py
你可以綁定
函數.
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
?對不起,不知道.但是您在 kivy 指南中使用了它.
Why use bind
? Sorry, no idea. But you it's used in the kivy guide.
這篇關于Python Kivy:如何在按鈕單擊時調用函數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!