[英]Linking a Kivy Button to Function
我不了解獼猴桃中的某些東西,希望有人可以照亮。 我已經在這個主題上做了大量的閱讀,但是似乎並沒有聯系到我。
我的問題來自將功能鏈接到kivy按鈕。 現在,我正在嘗試學習如何執行一個簡單的功能:
def Math():
print 1+1
我想做些更復雜的事情:
def Math(a,b):
print a^2 + b^2
其中a
和b
是來自kivy的輸入標簽,單擊按鈕時將打印答案。
這是我到目前為止的內容:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition
from kivy.uix.widget import Widget
from kivy.uix.floatlayout import FloatLayout
#######``Logics``#######
class Math(FloatLayout):
def add(self):
print 1+1
#######``Windows``#######
class MainScreen(Screen):
pass
class AnotherScreen(Screen):
pass
class ScreenManagement(ScreenManager):
pass
presentation = Builder.load_file("GUI_Style.kv")
class MainApp(App):
def build(self):
return presentation
if __name__ == "__main__":
MainApp().run()
這是我的獼猴桃語言文件:
import NoTransition kivy.uix.screenmanager.NoTransition
ScreenManagement:
transition: NoTransition()
MainScreen:
AnotherScreen:
<MainScreen>:
name: "main"
FloatLayout:
Button:
on_release: app.root.current = "other"
text: "Next Screen"
font_size: 50
color: 0,1,0,1
font_size: 25
size_hint: 0.3,0.2
pos_hint: {"right":1, "top":1}
<AnotherScreen>:
name: "other"
FloatLayout:
Button:
color: 0,1,0,1
font_size: 25
size_hint: 0.3,0.2
text: "add"
pos_hint: {"x":0, "y":0}
on_release: root.add
Button:
color: 0,1,0,1
font_size: 25
size_hint: 0.3,0.2
text: "Back Home"
on_release: app.root.current = "main"
pos_hint: {"right":1, "top":1}
<AnotherScreen>:
name: "other"
FloatLayout:
Button:
...
on_release: root.add <-- here *root* evaluates to the top widget in the rule.
這是AnotherScreen實例,但沒有add
方法。
class Math(FloatLayout):
def add(self):
print 1+1
在這里,您通過繼承FloatLayout
聲明了Math類, FloatLayout
是uix組件-小部件-。 並且您在此類add
上定義了一個方法。 仍然您沒有使用過它。 在kv文件中,您使用了FloatLayout
。
現在,為了使您能夠使用kv訪問函數,大多數時候,您可以使用root
/ self
或app
將其作為uix組件的一種方法來訪問,也可以將其導入,例如:
#: import get_color_from_hex kivy.utils.get_color_from_hex
<ColoredWidget>:
canvas:
Color:
rgba: get_color_from_hex("DCDCDC")
Rectangle:
size: self.size
pos: self.pos
所以你不能這樣:
<AnotherScreen>:
name: "other"
Math:
id: math_layout
Button:
...
on_release: math_layout.add()
或像這樣:
class AnotherScreen(Screen):
def add(self):
print(1+1)
如果您仍然無法解決此主題,我將很樂意提供更多幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.