如何在 Kivy 中从 python 代码更改屏幕
Posted
技术标签:
【中文标题】如何在 Kivy 中从 python 代码更改屏幕【英文标题】:How to change screens from python code in Kivy 【发布时间】:2021-05-24 20:54:15 【问题描述】:所以我正在为我的第一个严肃的 kivy 应用程序制作一个功能齐全的登录屏幕,我希望能够在用户按下按钮时更改窗口/屏幕。我通常知道在 KV 文件中我只会在发布时使用,但我希望发布时调用一种方法来验证用户凭据,如果这些凭据正确,则更改屏幕。那么我如何在 python 本身中调用屏幕管理器来更改屏幕?
from kivy.app import App
from kivy.lang.builder import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
class LoginLayout(Screen):
def login(self, **kwargs):
print("Login function working")
userEmail = self.ids.username.text
userPassword = self.ids.password.text
print(userEmail)
print(userPassword)
ScreenManager.current('emailWindow')
class EmailWindow(Screen):
pass
class WindowManager(ScreenManager):
pass
kv = Builder.load_file('loginScreen.kv')
class LoginScreen(App):
def build(self):
return kv
app = LoginScreen()
app.run()
千伏
ScreenManager:
LoginLayout:
EmailWindow:
<LoginLayout>:
name: 'loginWindow'
canvas.before:
Color:
rgba: (28/255, 102/255, 137/255, 1)
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
orientation: 'vertical'
size: root.width, root.height
Label:
text: 'Username'
font_name: 'Framd.ttf'
font_size: 20
TextInput:
id: username
multiline: False
size_hint: (.5, .3)
pos_hint: 'center_x' : .5
Label:
text: 'Password'
font_name: 'Framd.ttf'
font_size: 20
TextInput:
id: password
multiline: False
size_hint: (.5, .3)
pos_hint: 'center_x' : .5
Button:
text: 'Login'
size_hint: (.2, .8)
pos_hint: 'center_x' : 0.5
font_name: 'Framd.ttf'
on_release: root.login()
Button:
text: 'Create Account'
size_hint: (.2, .8)
pos_hint: 'center_x' : 0.5
font_name: 'Framd.ttf'
Button:
text: 'Forgot login Info'
size_hint: (.2, .8)
pos_hint: 'center_x' : 0.5
font_name: 'Framd.ttf'
<EmailWindow>:
name: 'emailWindow'
canvas.before:
Color:
rgba: (28/255, 102/255, 137/255, 1)
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
orientation: 'vertical'
size: root.width, root.height
Label:
text: 'To:'
font_name: 'Framd.ttf'
TextInput:
multiline: False
pos_hint: 'center_x': 0.5
size_hint: (.5, .3)
font_name: 'Framd.ttf'
Label:
text: 'Subject'
TextInput:
multiline: False
pos_hint: 'center_x': 0.5
size_hint: (.5, .3)
font_name: 'Framd.ttf'
Label:
text: 'Body'
font_name: 'Framd.ttf'
TextInput:
size_hint: (.5, .7)
pos_hint: 'center_x': 0.5
multiline: True
Button:
text: 'send'
size_hint: (.2, .8)
pos_hint: 'center_x' : 0.5
font_name: 'Framd.ttf'
【问题讨论】:
【参考方案1】:当Screen
被添加到ScreenManager
时,它会获得一个设置为ScreenManager
的manager
属性。所以在你的login()
方法中你可以这样做:
self.manager.current = 'emailWindow'
代替:
ScreenManager.current('emailWindow')
请注意,如上所述,使用 ScreenManager
引用的是 ScreenManager
类,而不是应用中的 ScreenManager
实例。
【讨论】:
以上是关于如何在 Kivy 中从 python 代码更改屏幕的主要内容,如果未能解决你的问题,请参考以下文章