我不了解奇异果中的某些东西,并希望有人可以照亮。我已经阅读了很多有关该主题的文章,但似乎并没有引起我的兴趣。
我的问题来自将功能链接到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()
这是我的 kivy 语言文件:
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
(是uix组件-小部件-)来声明了Math类。然后,您在此类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)
如果您在选择此主题时仍然遇到问题,我们将很乐意为您提供更多帮助。