问题描述
所以我正在为我的第一个严肃的 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()
KV
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,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'
解决方法
当 Screen
添加到 ScreenManager
时,它会获得一个 manager
属性设置为 ScreenManager
。因此,在您的 login()
方法中,您可以:
self.manager.current = 'emailWindow'
代替:
ScreenManager.current('emailWindow')
请注意,使用 ScreenManager
时,如上所述,会引用 ScreenManager
类,而不是应用中的 ScreenManager
实例。