I have made a simple app in kivymd. But I can not change screen on click on button inside kivymd. Everything works great. But when I click on button then it popup toast also but screen is not changing. What will be changes or better implementation for this?
app.py
from kivymd.app import MDApp
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.lang import Builder
from main_screen_str import helper_string
from kivy.core.window import Window
from kivymd.toast import toast
from kivymd.uix.bottomsheet import MDGridBottomSheet
Window.size = (300, 500)
class MainScreen(Screen):
pass
class SettingsScreen(Screen):
pass
class AboutScreen(Screen):
pass
class MainApp(MDApp):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.sm = ScreenManager()
self.sm.add_widget(MainScreen(name="main_screen"))
self.sm.add_widget(SettingsScreen(name="settings_screen"))
self.sm.add_widget(AboutScreen(name="about_screen"))
self.main_str = Builder.load_string(helper_string)
def build(self):
screen = Screen()
screen.add_widget(self.main_str)
return screen
def callback_for_menu_items(self, *args):
if args[0] == 'Home':
toast(args[0])
self.sm.current = "main_screen"
if args[0] == 'Settings':
toast(args[0])
self.sm.current = "settings_screen"
if args[0] == 'About':
toast(args[0])
self.sm.current = "about_screen"
def show_example_grid_bottom_sheet(self):
self.bottom_sheet_menu = MDGridBottomSheet()
data = {
"Home": "home",
"Settings": "settings",
"About": "information-outline",
}
for item in data.items():
self.bottom_sheet_menu.add_item(
item[0],
lambda x, y=item[0]: self.callback_for_menu_items(y),
icon_src=item[1],
)
self.bottom_sheet_menu.open()
if __name__ == '__main__':
MainApp().run()
This builder string to create screen.
Are there any better solution for this?
builder string
helper_string = """
ScreenManager:
MainScreen:
SettingsScreen:
AboutScreen:
<MainScreen>:
name: 'main_screen'
MDIconButton:
icon: "menu"
theme_text_color: "Custom"
text_color: 1,0,0,1
on_press: app.show_example_grid_bottom_sheet()
<SettingsScreen>:
name: 'settings_screen'
<AboutScreen>:
name: 'about_screen'
"""
In your __init__() method of the App, you are building self.sm with the lines:
self.sm = ScreenManager()
self.sm.add_widget(MainScreen(name="main_screen"))
self.sm.add_widget(SettingsScreen(name="settings_screen"))
self.sm.add_widget(AboutScreen(name="about_screen"))
But self.sm is not used as part of your GUI. So your changes to self.sm has no effect on your GUI. The line following that:
self.main_str = Builder.load_string(helper_string)
basically does exactly the same thing as the previous lines.
Then in your build() method, you are creating a new Screen and adding the self.main_str as a child of that Screen.
While you can have a ScreenManager as a child of a Screen, in your posted example that does not seem to serve any purpose.
Here is a modified version of part of the MainApp that I think will do what you want:
class MainApp(MDApp):
# def __init__(self, **kwargs):
# super().__init__(**kwargs)
# self.sm = ScreenManager()
# self.sm.add_widget(MainScreen(name="main_screen"))
# self.sm.add_widget(SettingsScreen(name="settings_screen"))
# self.sm.add_widget(AboutScreen(name="about_screen"))
#
# self.main_str = Builder.load_string(helper_string)
def build(self):
self.sm = Builder.load_string(helper_string)
return self.sm
# screen = Screen()
# screen.add_widget(self.main_str)
# return screen
The above code greatly simplifies the build() method, eliminates the __init__() method, and now self.sm is actually part of the GUI.
Note that when you load a kv string that has a root node with Builder.load_string(), that root node is created and returned. The lines in your kv string:
ScreenManager:
MainScreen:
SettingsScreen:
AboutScreen:
result in a ScreenManager instance being created along with the three children listed for it, so the code in your __init__() method was duplicating that.
Related
EDIT: so this is a very simple version of what it is like in my app but i think you get the point. Basically i want to destroy the Buttons created in the for loop with the Button on the destroywidgets screen.
.kv:
MainWindow:
<MainWindow>
FloatLayout:
size_hint: 1, .1
Button:
text:"next screen"
size_hint:.1,1
pos_hint:{"x": 0, "y": 0}
on_release: app.root.current = "destroywidgets"
Button:
text:"laodwidgets"
on_release: root.create_widgets()
size_hint:.1, 1
pos_hint:{"x": .5, "y": 0}
.py:
from kivy.app import App
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.scrollview import ScrollView
class MainWindow(Screen):
name = "mainwindow"
def __init__(self, **kwargs):
super(MainWindow, self).__init__()
self.scrl_view_1 = ScrollView(
size_hint_y=.85,
pos_hint={"x": 0, "y": .15},
do_scroll_x=False,
do_scroll_y=True,
size_hint_x=1
)
self.scrl_child_1 = GridLayout(
size_hint_x=1,
size_hint_y=None,
cols=2,
height=1000,
row_default_height=150,
row_force_default=True
)
self.add_widget(self.scrl_view_1)
self.scrl_view_1.add_widget(self.scrl_child_1)
def create_widgets(self):
print("creating widgets")
for i in range(0, 6):
btn = Button(
text=str(i)
)
self.scrl_child_1.add_widget(btn)
print("added")
class DestroyWidgets(Screen):
name = "destroywidgets"
def __init__(self, **kwargs):
super(DestroyWidgets, self).__init__()
btn_destroy_widgets = Button(
text="Destroy children of Mainwindow",
#some on release function to clear all children from scrl_child_1 in Mainwindow
)
self.add_widget(btn_destroy_widgets)
class ShoppingList(App):
def build(self):
self.sm = ScreenManager()
self.sm.add_widget(MainWindow(name="mainwindow"))
self.sm.add_widget(DestroyWidgets(name="destroywidgets"))
return self.sm
if __name__ == "__main__":
main_app = ShoppingList()
main_app.run()
So I have to reference a GridLayout which is inside of a ScrollView created in class A in class B. Since you cannot give Layouts an ID in python code and reference it with self.ids i can't figure out how to do it. I tried suggestions from another post with the weakref.ref method as example but i couldn't get it to work. The whole point is that i have to destroy all children of Layouts from other classes in a function somehow.
Heres just a little snippet of my code which i think will be enough. If you need more just write me. Thanks for all the help in advance!
class SelfMadePlans(Screen):
name = "selfmadeplans"
def __init__(self, **kwargs):
super(SelfMadePlans, self).__init__()
self.scrl_view_2 = ScrollView(
size_hint_y=.85,
pos_hint={"x": 0, "y": 0},
do_scroll_x=False,
do_scroll_y=True,
size_hint_x=1
)
self.scrl_child_2 = GridLayout(
size_hint_x=1,
size_hint_y=None,
cols=3,
height=20000,
row_default_height=150,
row_force_default=True,
)
self.add_widget(self.scrl_view_2)
self.scrl_view_2.add_widget(self.scrl_child_2)
and then something in another class like:
class B:
def destroy_children(self):
MDApp.get_running_app().sm.get_screen("selfmadeplans").ids.scrl_child_2.children.clear()
First of all you must pass var. no. of kwargs in __init__ in order to use and get all the default functionalities.
...
def __init__(self, **kwargs):
super(MainWindow, self).__init__(**kwargs)
...
etc.
Next to access certain screen from ScreenManager you can use method get_screen as follows,
...
btn_destroy_widgets = Button(
text="Destroy children of Mainwindow",
#some on release function to clear all children from scrl_child_1 in Mainwindow
)
btn_destroy_widgets.bind(on_release = self.destroy_widgets_on_main)
self.add_widget(btn_destroy_widgets)
def destroy_widgets_on_main(self, *args):
main_window = self.manager.get_screen("mainwindow")
main_window.scrl_child_1.clear_widgets()
What I want to do is to switch the screen when the "join" button is pressed.
This is what I have written.
import kivy
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
class ConnectingPage(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.cols = 2
self.add_widget(Label(text = "Usename:"))
self.username = TextInput(multiline=False)
self.add_widget(self.username)
self.add_widget(Label(text = "Password:"))
self.password = TextInput(multiline=False,password = True)
self.add_widget(self.password)
self.joinbutton = Button(text="Join")
self.joinbutton.bind(on_press = self.click_join_button)
self.add_widget(Label())
self.add_widget(self.joinbutton)
def click_join_button(self, instance):
username = self.username.text
password = self.password.text
info = "you can enter"
MyApp.screen_manager.current = "Info"
# Simple information/error page
class InfoPage(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.cols = 1
self.message = Label(text = "welcome",halign="center", valign="middle", font_size=30)
self.add_widget(self.message)
class MyApp(App):
def build(self):
self.screen_manager = ScreenManager()
self.connecting_page = ConnectingPage()
screen = Screen(name='Connect')
screen.add_widget(self.connecting_page)
# Info page
self.info_page = InfoPage()
screen = Screen(name='Info')
screen.add_widget(self.info_page)
return ConnectingPage()
MyApp().run()
Everything works fine in the starting but when the button "join" is pressed, this is the error:
AttributeError: type object 'MyApp' has no attribute 'self'
Please suggest what to do next.
Your build() method returns ConnectingPage(), so your App is not actually using a ScreenManager. All the code in that build() method (except that return) has no effect. Here is a modified version of your MyApp class that actually uses ScreenManager:
class MyApp(App):
screen_manager = ScreenManager() # this make screen_manager a class vaiable
def build(self):
# self.screen_manager = ScreenManager()
self.connecting_page = ConnectingPage()
screen = Screen(name='Connect')
screen.add_widget(self.connecting_page)
self.screen_manager.add_widget(screen) # add screen to ScreenManager
# Info page
self.info_page = InfoPage()
screen = Screen(name='Info')
screen.add_widget(self.info_page)
self.screen_manager.add_widget(screen) # add screen to ScreenManager
# return ConnectingPage()
return self.screen_manager
This allows your code:
MyApp.screen_manager.current = "Info"
to work, but it is an odd construction.
A more typical construction would be something like this:
class MyApp(App):
def build(self):
screen_manager = ScreenManager()
connecting_page = ConnectingPage()
screen = Screen(name='Connect')
screen.add_widget(connecting_page)
screen_manager.add_widget(screen) # add screen to ScreenManager
# Info page
info_page = InfoPage()
screen = Screen(name='Info')
screen.add_widget(info_page)
screen_manager.add_widget(screen) # add screen to ScreenManager
# return ConnectingPage()
return screen_manager # return the ScreenManager
But this requires a change in the code that changes the Screen:
App.get_running_app().root.current = "Info"
My class OrderManagementScreen is firstly instantiated by Builder.load_file and then by sm.add_widget(OrderManagementScreen(name='order_management')).
I would like to be able to access the instance created by Builder.load_file - how can I do this?
This post is the closest I could find, but when I do MDApp.get_running_app().root it returns None.
app.py: (mixture of attempts in my update_database function)
import atexit
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
from order_management.constants import HELP_TEXT
from order_management.presentation.order_management.order_management_view import OrderManagementScreen
from order_management.presentation.components.dialog import Dialog
from order_management.data.query import Query
class App(MDApp):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.screen = Builder.load_file(
"order_management/presentation/main.kv")
self._query = Query()
something = MDApp.get_running_app()
self._dialog = Dialog()
def build(self):
self.theme_cls.primary_palette = "Green"
sm = ScreenManager()
# Instantiates OrderManagementScreen.py
sm.add_widget(OrderManagementScreen(name='order_management'))
return self.screen
def handle_menu_click(self):
self._dialog.render_dialog("Usage Guide:", HELP_TEXT, None, None)
def update_database(self):
# order_management_screen = MDApp.get_running_app().screen.children[0].manager.get_screen('order_management')
# order_management_screen = self.screen.get_screen('order_management')
self.order_management_screen.update_database()
if __name__ == "__main__":
App().run()
main_app = App()
atexit.register(main_app.update_database) # Calls update_database on exit.
main.kv:
#:kivy 1.11.0
#:include order_management/presentation/order_management/order_management_ui.kv
# Having to use v1.11.0 because of bug relating to MDDataTable
<Toolbar#AnchorLayout>:
AnchorLayout:
anchor_x: 'center'
anchor_y: 'top'
MDToolbar:
title: 'Order Management App'
specific_text_color: app.theme_cls.accent_color
right_action_items: [['help-circle', lambda x: app.handle_menu_click()]]
elevation: 9
ScreenManager:
OrderManagementScreen:
Toolbar:
order_management_ui.kv:
#:kivy 1.11.0
# Having to use v1.11.0 because of bug relating to MDDataTable
<OrderManagementScreen>:
name: 'order_management'
id: order_management
GridLayout:
cols: 1
pos_hint: {'top': 0.85}
ScrollView:
id: table_container
I guess it goes to show how sometimes you just need to step away from the computer and come back with fresh eyes...
My solution was to simply store the instance of app when run so that when I called my update_database function is was looking at the correct instance - and therefore could access the instance of a screen class the kivy had created with:
self.root.children[0].manager.get_screen('order_management')
I use children[0] here because this is the first screen I added to ScreenManager, and 'order_management' is the name of the screen obviously.
I hope that this by chance does help someone else.
New app.py:
import atexit
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
from order_management.constants import HELP_TEXT
from order_management.presentation.order_management.order_management_view import OrderManagementScreen
from order_management.presentation.components.dialog import Dialog
from order_management.data.query import Query
class App(MDApp):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.screen = Builder.load_file(
"order_management/presentation/main.kv")
self._query = Query()
self._dialog = Dialog()
def build(self):
self.theme_cls.primary_palette = "Green"
sm = ScreenManager()
sm.add_widget(OrderManagementScreen(name='order_management'))
return self.screen
def handle_menu_click(self):
self._dialog.render_dialog("Usage Guide:", HELP_TEXT, None, None)
def update_database(self):
order_management_screen = self.root.children[0].manager.get_screen('order_management')
order_management_screen.update_database()
if __name__ == "__main__":
app = App()
app.run()
atexit.register(app.update_database) # Calls update_database on exit.
I am trying to figure out how to only change the screen direction animation in kivy for one certain button press(cancel button which should wipe right instead of left like a forward-navigating button.) Here is what I am doing currently to make this happen:
# Cancel Button
self.cancel = Button(text="Cancel", height=30, width=90,size_hint=(None, None),pos=(300, 350))
self.cancel.bind(on_release=self.BackFunction)
self.ids.float_web.add_widget(self.cancel)
def BackFunction(self, *args):
self.manager.transition.direction = 'right'
self.manager.current = ('input_sc')
I am wondering how to reset the direction to left after this animation happens. If I follow the screen change with
self.manager.transition.direction = 'left'
then it simply makes the direction left inside of BackFunction
Thanks
I think it's best to define the direction property each time you change thecurrent attribute. However, you can do what you want to do binding a function to on_complete event and unbind within the function itself:
Example:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
kv_text='''\
#:import SlideTransition kivy.uix.screenmanager.SlideTransition
<MyScreenManager>:
transition: SlideTransition()
FirstScreen:
LastScreen:
<FirstScreen#Screen>:
name: 'first_sc'
BoxLayout:
Button:
text: 'Next'
on_release: root.next_screen()
<LastScreen#Screen>:
name: 'last_sc'
BoxLayout:
Button:
text: 'Previous'
on_release: root.previous_screen()
'''
class MyScreenManager(ScreenManager):
pass
class FirstScreen(Screen):
def __init__(self, **kwargs):
super(FirstScreen, self).__init__(**kwargs)
def next_screen(self, *args):
self.manager.current = 'last_sc'
class LastScreen(Screen):
def __init__(self, **kwargs):
super(LastScreen, self).__init__(**kwargs)
def previous_screen(self, *args):
self.manager.transition.direction = 'right'
self.manager.current = 'first_sc'
self.manager.transition.bind(on_complete=self.restart)
def restart(self, *args):
self.manager.transition.direction = 'left'
self.manager.transition.unbind(on_complete=self.restart)
class MySubApp(App):
def build(self):
return MyScreenManager()
def main():
Builder.load_string(kv_text)
app = MySubApp()
app.run()
if __name__ == '__main__':
main()
I'm trying to execute this:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.audio import SoundLoader,Sound
from kivy.lang import Builder
Builder.load_string('''
<MenuPage>:
BoxLayout:
orientation:'vertical'
Button:
text:'play'
on_press:root.plays()
Button:
text:'stop'
on_press:root.stops()
''')
class Music(Sound):
def __init__(self):
self.sound = SoundLoader.load('/home/hosein/Music/Man.mp3')
class MenuPage(Screen):
def __init__(self):
self.M = Music()
def plays(self):
self.M.play()
def stops(self):
self.M.stop()
music = Music()
sm = ScreenManager()
menu = MenuPage(name='menu')
sm.add_widget(menu)
class TestApp(App):
def build(self):
return sm
TestApp().run()
https://gist.github.com/daryasary/f69e1d0444ae70ff5296
There should be just two buttons to play or stop a song.
But it doesn't work. What is the solution?
Also, is there any way to make the play and stop buttons into a single button, where the first touch plays the song and the second stops it?
If you want to use one button, you could try using Kivy's ToggleButton and play music when the toggle button's state is 'down' and not play music when the state is 'normal'.
<MenuPage>:
BoxLayout:
orientation:'vertical'
ToggleButton:
id: music_button
text:'play'
on_press:root.play_or_stop()
''')
class MenuPage(Screen):
def __init__(self):
self.M = Music()
def play_or_stop(self):
if self.music_button.state == 'down':
self.music_button.text = "Stop"
self.M.play()
else:
self.music_button.text = "Play"
self.M.stop()
Or, you could use a regular button that sets a variable to either True or False each time it's pressed. You can then have this value determine whether the music plays or stops.
The problem is that you're using Sound wrong. You should not be subclassing Sound or trying to create a new instance directly.
SoundLoader.load returns a Sound instance created using one of the available audio providers - this should be used instead. Try something like this:
class MenuPage(Screen):
def __init__(self):
self.M = SoundLoader.load('/home/hosein/Music/Man.mp3')
def plays(self):
self.M.play()
def stops(self):
self.M.stop()
def toggle(self):
self.M.state = 'play' if self.M.state == 'stop' else 'play'
return self.M.state
it should be something like this:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.audio import SoundLoader,Sound
from kivy.lang import Builder
Builder.load_string('''
<MenuPage>:
BoxLayout:
orientation:'vertical'
Button:
text:'song'
on_press:root.plays()
''')
class MenuPage(Screen):
M = SoundLoader.load('/home/hosein/Music/Man.mp3')
def plays(self):
if MenuPage.M.state == 'stop':
MenuPage.M.play()
else:
MenuPage.M.stop()
sm = ScreenManager()
menu = MenuPage(name='menu')
sm.add_widget(menu)
class TestApp(App):
def build(self):
return sm
TestApp().run()