<h2>模式:<code>.kv</code></h2>
<p>很简单,<code>say_hello</code>属于<code>Launch</code>类,因此要在<code>.kv</code>文件中使用它,必须编写<code>root.say_hello</code>。请注意,<code>say_hello</code>是一个要执行的函数,因此您不必忘记<code>()</code>--->;<code>root.say_hello()</code>。</p>
<p>另外,如果<code>say_hello</code>在<code>App</code>类中,则应该使用<code>App.say_hello()</code>,因为它属于应用程序。(注意:即使你的应用程序类是<code>class MyFantasicApp(App):</code>,它也总是<code>App.say_hello()</code>或<code>app.say_hello()</code>我不记得了,对不起)。</p>
<pre><code>#:kivy 1.9.1
<Launch>:
BoxLayout:
Button:
size:(80,80)
size_hint:(None,None)
text:"Click me"
on_press: root.say_hello()
</code></pre>
<h2>模式:<code>.py</code></h2>
<p>您可以<code>bind</code>函数。</p>
<pre><code>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"
</code></pre>
<p>为什么要使用<code>bind</code>?对不起,不知道。但你在<a href="https://kivy.org/docs/api-kivy.uix.button.html" rel="noreferrer">the kivy guide</a>中用过。</p>