Reputation: 151
I have a button which was made in python file and I have been trying to make it so it changes screens from one to another.
def callback(instance):
print("Test 1")
sm = ScreenManager()
sm.add_widget(ScreenTwo(name="ScreenTwo"))
print("Test2")
class ScreenOne(Screen):
def on_enter(self):
self.add_widget(ImageURLButton(source=icon2, size=(100,100), size_hint=(0.1, 0.1), on_press=callback, pos_hint={"x":0.90, "top":1.0}))
class ScreenTwo(Screen):
pass
class ScreenManagement(ScreenManager):
pass
When I do click the button all it does it prints "Test1" and "Test2" without it changing the screen. Sorry if this is really obvious to others but I do not know how to fix it, could anyone help me please?
Upvotes: 1
Views: 641
Reputation: 39092
Would be better if you posted a MCVE, but I made one myself. Here is how it can be done:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
def callbackTo2(instance):
sm.current="ScreenTwo"
def callbackTo1(instance):
sm.current="ScreenOne"
class ScreenOne(Screen):
def __init__(self, *args):
super(ScreenOne, self).__init__(name='ScreenOne')
self.add_widget(Button(text='Switch To Screen Two', size_hint=(0.1, 0.1), on_press=callbackTo2, pos_hint={"x":0.90, "top":1.0}))
class ScreenTwo(Screen):
def __init__(self, *args):
super(ScreenTwo, self).__init__(name='ScreenTwo')
self.add_widget(Button(text='Switch To Screen One', size_hint=(0.1, 0.1), on_press=callbackTo1, pos_hint={"x":0.90, "top":1.0}))
sm = ScreenManager()
class ScreenPlayApp(App):
def build(self):
sm.add_widget(ScreenOne())
sm.add_widget(ScreenTwo())
return sm
if __name__ == '__main__':
app = ScreenPlayApp()
app.run()
Note that there is only one ScreenManager instance, all the screens can be added to the ScreenManager initially, and screens are switched by using sm.current=
. Also, you can build your Screen in its __init__()
method. Using the on_enter
causes the members of the screen to be rebuilt each time the screen is displayed. Also, you cannot use both 'size' and 'size_hint' for the same widget unless you are setting 'size_hint' to 'None'.
Upvotes: 4