python - Python KivyMD:如何使用按钮调用函数?
问题描述
我是 kivy 和 kivyMD 的新手,我试图调用一个函数来打印用户的电子邮件和密码。我如何在这段代码中绑定函数或使用 on_press?我尝试使用 on_pressed:root.function() 方法,但它不起作用,因为我的函数没有写在 pre-emade ScreenManager 中
.PY
import...
Builder.load_string("""
#:include kv/login.kv
#:import utils kivy.utils
#:import images_path kivymd.images_path
""")
class MyApp(MDApp):
def __init__(self, **kwargs):
self.title = "iKarate"
self.theme_cls.theme_style = "Light"
self.theme_cls.primary_palette = "Blue"
self.sm = ScreenManager()
super().__init__(**kwargs)
def build(self):
self.sm.add_widget(Factory.LoginScreen())
return self.sm
def doThis(self):
email = self.email
password = self.password
print(email, password)
if __name__ == "__main__":
MyApp().run()
.KV
#:kivy 1.11.1
<LoginScreen@Screen>:
name: "login"
BackgroundLayer:
#MDCard:
MDCard:
orientation: "vertical"
size_hint: [0.8, 0.6]
pos_hint: {"center_x": 0.5, "center_y": 0.6}
BoxLayout:
orientation: "vertical"
MDLabel:
text: "Welcome to the log in page"
text_size: self.size
font_size: 25
bold: True
halign: "center"
valign: "middle"
Image:
size_hint_y: 10
source: "kv/image.png"
MDTextField:
id: email
hint_text: "E-mail"
MDTextField:
id: password
hint_text: "Password"
password: True
MDFillRoundFlatButton:
id: btn
text: "Sign In"
width: dp(200)
pos_hint: {"center_x": .5}
on_press:print("pressed")
<BackgroundLayer@BoxLayout>:
orientation: "vertical"
BoxLayout:
orientation: "vertical"
canvas.before:
Color:
rgba: utils.get_color_from_hex("#00146e")
Rectangle:
pos: 0, self.center_y + self.height/3 - 50
size: (self.width,70)
BoxLayout:
orientation: "horizontal"
on_press:print("pressed") 成功打印 "pressed"
解决方案
如果您从App
类中调用函数,请使用它:
on_press: app.doThis()
如果您从Screen
类中调用函数,请使用它:
on_press: root.doThis()
推荐阅读
- logical-operators - 逻辑运算 !A && !B vs !(A||B)
- c# - 在 WCF 中使用 Certificate 和 UserName 进行客户端身份验证,使用 basicHttpsBinding 传递反向代理身份验证
- google-cloud-platform - BigQuery 使用 Datastore 导出文件直接从 Storage 查询数据
- ruby-on-rails - Docker 错误 Getaddrinfo: Name or service not known in Puma Nginx server-Mac os
- mysql - Windows 10中的Mysql 8.0安装错误
- jmeter - 让 Jmeter 报告错误失败
- javascript - 在 iffe 中访问“this”上下文
- here-api - 此处地图中两点距离计算的单位是什么?
- mysql - 喜欢“%伟哥%”
- javascript - 如何在javascript中使用正则表达式仅删除最后一个新行