[英]Can someone tell me where I'm going wrong with this structure?
我正在嘗試從我的.kv調用函數,但是我找不到在繪制小部件的函數之外引用函數的正確方法。 我已經嘗試過root.dostuff父...我...我的App ...我的應用...我可以將該函數放入Widgets類中,但這會破壞其他內容...
MyApp.py
class Widgets(Widget):
pass
def dostuff(x):
print(x)
class MyApp(App):
def build(self):
global w
print("Build")
w = Widgets()
return w
if __name__ == "__main__":
MyApp().run()
MyApp.kv:
Button:
text: "Press Me"
on_press: dostuff(1)
你有兩個問題。 首先是函數dostuff
未在kv文件中定義。 您可以使用#:import dostuff MyApp.dostuff
導入它,或使其成為例如app類的方法,然后使用app.dostuff()
調用。
另外,您的kv文件實際上並未加載。 要加載它,並且不顯示它會產生的按鈕,因此您的示例實際上不會演示您的問題。 將文件my.kv
為my.kv
使其自動加載,並且不從構建方法返回任何內容以將Button用作根窗口小部件。
在繪制窗口小部件的函數之外引用函數的正確方法。
您還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()
my.kv:
<MyButton>:
text: "Press Me"
或者, on_press() inside the kv file
使用on_press() inside the kv file
:
my.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父母...自我... MyApp ...應用程序。
root
和app
在kv文件中的工作方式如下:
my.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
:
my.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類中,但這會破壞其他內容。
好吧,不要讓函數那樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.