<blockquote>
<p>the correct way to reference a function outside the function that
draws the widgets.</p>
</blockquote>
<p>您还可以<code>define on_press() outside the kv file</code>:</p>
<pre><code>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()
</code></pre>
<p>你知道吗my.kv地址:</p>
<pre><code><MyButton>:
text: "Press Me"
</code></pre>
<p>或者,用<code>on_press() inside the kv file</code>:</p>
<p>你知道吗my.kv地址:</p>
<pre><code><MyButton>:
text: "Press Me"
on_press: self.dostuff(10, 20) #Look in MyButton class for dostuff()
</code></pre>
<hr/>
<pre><code>...
...
class MyButton(Button):
def dostuff(self, *args):
print(args)
...
...
</code></pre>
<blockquote>
<p>I've tried root.dostuff parent... self... MyApp... App.</p>
</blockquote>
<p>以下是<code>root</code>和<code>app</code>在kv文件中的工作方式:</p>
<p>你知道吗my.kv地址:</p>
<pre><code><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
</code></pre>
<hr/>
<pre><code>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()
</code></pre>
<p>或者,您可以<code>put the function inside the App class</code>:</p>
<p>你知道吗my.kv地址:</p>
<pre><code><MyButton>:
text: "Press Me"
on_press: app.dostuff('hello', 22)
</code></pre>
<hr/>
<pre><code>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()
</code></pre>
<blockquote>
<p>I could put the function into the Widgets class, but that breaks other
stuff...</p>
</blockquote>
<p>好吧,别让函数那样做。你知道吗</p>