Here is my code:
from kivymd.app import MDApp
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
n = 1
class Screen1(Screen):
pass
class Screen2(Screen):
def set_number(self, n):
self.ids["number"].text == f"{n}"
print(f"The n variabile value is: {n}")
txt = self.ids["number"].text
print(f"The displayed number is: {txt}\n")
return
sm = ScreenManager()
sm.add_widget(Screen1(name="Screen1"))
sm.add_widget(Screen2(name="Screen2"))
class TestApp(MDApp):
def build(self):
self.title = "Test app"
self.theme_cls.primary_palette = "Indigo"
self.theme_cls.primary_hue = "600"
screen = Builder.load_file("test.kv")
return screen
def arrow_up(self):
global n
if n == 5:
pass
else:
n += 1
Screen2().set_number(n)
def arrow_down(self):
global n
if n == 1:
pass
else:
n -= 1
Screen2().set_number(n)
if __name__ == '__main__':
TestApp().run()
And here my KV file:
ScreenManager:
id: scrn_mngr
Screen1:
Screen2:
<Screen1>:
id: Scrn1
name: "Screen1"
MDRectangleFlatIconButton:
text: "Next screen"
icon: "arrow-right"
pos_hint: {"center_x": .5, "center_y": .5}
width: dp(180)
on_press: root.manager.current = "Screen2"
<Screen2>
id: Scrn2
name: "Screen2"
MDFloatingActionButton:
icon: "arrow-up-bold-outline"
md_bg_color: app.theme_cls.primary_color
pos_hint: {"center_x": .4, "center_y": .5}
on_press: app.arrow_up()
MDFloatingActionButton:
icon: "arrow-down-bold-outline"
md_bg_color: app.theme_cls.primary_color
pos_hint: {"center_x": .6, "center_y": .5}
on_press: app.arrow_down()
MDLabel:
text: "Number"
halign: "center"
pos_hint: {"center_x": .5, "center_y": .55}
MDLabel:
id: number
text: "1"
halign: "center"
pos_hint: {"center_x": .5, "center_y": .5}
I'm trying to increase and decrease the variable n using the two MDFloatingActionButton on the second screen. The problem is that the text property of the MDLabel does not change as n increase or decrease, and always display the number one, even if n actually change correctly. I can't figure out what's wrong, can someone help me? Thanks!
The lines:
will have no effect on your GUI. When you use
Screen2()
you are creating a new instance ofScreen2
which has no relation to the one displayed in your GUI. So callingScreen2().set_number(n)
is settingn
in an instance ofScreen2
that is not displayed in your GUI.There are several ways to fix this. One way is to just move the
arrow_up()
andarrow_down()
methods into theScreen2
class like this:Then in the 'kv' change
app.arrow_down()
andapp.arrow_up()
to refer toroot
instead ofapp
: