I am working on a login system with python, kivymd, and kivy's screenmanager to switch, however, when I try to switch the screen from the login screen to another one nothing happens, no errors, and no visual changes. This is a reproducible example:
.py file
import kivy
from kivy.uix.image import Image
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivymd.app import MDApp
class Screen1(Screen):
def SwitchScreen(self):
scrMng.current = "screen2"
class Screen2(Screen):
def SwitchScreen(self):
scrMng.current = "screen1"
scrMng = ScreenManager()
scrMng.add_widget(Screen1(name = "screen1"))
scrMng.add_widget(Screen2(name = "screen2"))
class TestApp(MDApp):
def build(self):
return Builder.load_file("main.kv")
TestApp().run()
.kv file
ScreenManager:
Screen1:
Screen2:
<Screen1>
name: "screen1"
MDCard:
size_hint: None, None
size: 300, 350
pos_hint: {"center_x": 0.5, "center_y": 0.5}
elevation: 10
padding: 25
spacing: 25
orientation: 'vertical'
MDLabel:
text: "Screen2"
font_size: 40
halign: "center"
font_bold: True
theme_text_color: "Custom"
text_color: (0.20, 0.33, 1.00, 1)
MDRoundFlatButton:
text: "SWITCH"
font_size: 12
pos_hint: {"center_x": 0.5}
on_press: self.parent.parent.SwitchScreen()
<Screen2>
name: "screen2"
MDCard:
size_hint: None, None
size: 300, 350
pos_hint: {"center_x": 0.5, "center_y": 0.5}
elevation: 10
padding: 25
spacing: 25
orientation: 'vertical'
MDLabel:
text: "Screen1"
font_size: 40
halign: "center"
font_bold: True
theme_text_color: "Custom"
text_color: (0.20, 0.33, 1.00, 1)
MDRoundFlatButton:
text: "SWITCH"
font_size: 12
pos_hint: {"center_x": 0.5}
on_press: self.parent.parent.SwitchScreen()
Python version: 3.9.9 Kivy version: 2.0.0
Any help is appreaciated!
CodePudding user response:
You are creating a GUI using the lines:
scrMng = ScreenManager()
scrMng.add_widget(Screen1(name = "screen1"))
scrMng.add_widget(Screen2(name = "screen2"))
But the scrMng
created above is never used, so those lines can be eliminated. And the reference to scrMng
in the python code will do nothing, since scrMng
is not actually part of your app.
Your GUI is actually created by the line:
return Builder.load_file("main.kv")
Then the Screen
classes can become:
class Screen1(Screen):
def SwitchScreen(self):
self.manager.current = "screen2"
class Screen2(Screen):
def SwitchScreen(self):
self.manager.current = "screen1"
Note that self.manager
in a Screen
class is always a reference to its ScreenManager
.