单击任意按钮后,我需要打开一个新屏幕,然后关闭主屏幕。可以吗?
逻辑:
if i click in b4 do > close the MAIN SCREEN and open a new empty screen.
我尝试了Internet上的一些教程,但我想在不使用kv文件的情况下执行此操作。
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
class Grid(GridLayout):
def __init__(self, **kwargs):
super(Grid, self).__init__(**kwargs)
self.rows= 3
self.title = Label(text='MAIN SCREEN')
self.add_widget(self.title)
self.MainGrid = GridLayout()
self.MainGrid.cols = 2
self.b4 = Button(text="#b4")
self.MainGrid.add_widget(self.b4)
self.b4.bind(on_press=self.newScreen)
self.add_widget(self.MainGrid)
def newScreen(self, instance):
pass
class MyApp(App):
def build(self):
return Grid()
if __name__ == "__main__":
MyApp().run()
答案 0 :(得分:1)
您没有任何屏幕,所以您无法更改它,而是有一个主窗口。解决方案是将ScreenManager设置为顶层,添加必要的Screen,并在第一个Screen中添加Grid类的对象,并进行绑定,以便将“当前”属性更改为您要使用的Screen的名称。想显示
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
class Grid(GridLayout):
def __init__(self, **kwargs):
super(Grid, self).__init__(**kwargs)
self.rows = 3
self.title = Label(text="MAIN SCREEN")
self.add_widget(self.title)
self.MainGrid = GridLayout()
self.MainGrid.cols = 2
self.b4 = Button(text="#b4")
self.MainGrid.add_widget(self.b4)
self.add_widget(self.MainGrid)
class MyScreenManager(ScreenManager):
def __init__(self, **kwargs):
super(MyScreenManager, self).__init__(**kwargs)
self.main_screen = Screen(name="main_screen")
self.new_screen = Screen(name="new_screen")
self.add_widget(self.main_screen)
self.add_widget(self.new_screen)
grid = Grid()
grid.b4.bind(on_press=self.change_screen)
self.main_screen.add_widget(grid)
def change_screen(self, *args):
self.current = "new_screen"
class MyApp(App):
def build(self):
return MyScreenManager()
if __name__ == "__main__":
MyApp().run()