我正在尝试为Kivy中的按钮添加功能,但它无法正常工作。
这是python文件的代码:
import kivy
kivy.require("1.9.1")
from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
class MainMenuApp(App):
def build(self):
return BoxLayout()
def Play(self):
print("Play Button Pressed")
def LeaderBoards(self):
print("Leader Board Button Pressed")
def Credits(self):
print("Credits Button Pressed")
def Settings(self):
print("Settings Button Pressed")
if __name__ == "__main__":
MainMenuApp().run()
对于kv文件:
<BoxLayout>:
orientation: "vertical"
spacing: 20
padding: 60, 40
Label:
font_name: "TitleFont.ttf"
font_size: "60sp"
text: "Game Title"
size_hint: 1, 2
Button:
background_down: "Blue.jpg"
background_normal: "Red.jpg"
font_name: "TitleFont.ttf"
font_size: "30sp"
text: "Play"
Button:
background_down: "Blue.jpg"
background_normal: "Red.jpg"
font_name: "TitleFont.ttf"
font_size: "30sp"
text: "LeaderBoards"
Button:
background_down: "Blue.jpg"
background_normal: "Red.jpg"
font_name: "TitleFont.ttf"
font_size: "30sp"
text: "Credits"
Button:
background_down: "Blue.jpg"
background_normal: "Red.jpg"
font_name: "TitleFont.ttf"
font_size: "30sp"
text: "Settings"
此代码生成如下屏幕:Image
我知道我需要使用on_click或on_release方法,但我不知道如何将它连接到我的Python文件中的函数。 我的问题与本网站上的其他问题不同,因为它使用kv语言和Python而不仅仅是Python
答案 0 :(得分:2)
创建自定义类,然后按root.attribute
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
Builder.load_string('''
<MyLayout>:
Button:
text: 'Try me!'
on_release: root.button_pressed()
''')
class MyLayout(BoxLayout):
def button_pressed(self):
print("Button pressed")
class MyApp(App):
def build(self):
return MyLayout()
MyApp().run()