This code actually worked until I added multiple screens. It still works when I remove the multi Screen Manager. I get the attrubite error point to Chapter ids
Im trying to add a chapters screen. What Im I doing wrong please.
I think the error is from self.root.ids. I may be wrong. Below is thwe code
Python
from kivymd.app import MDApp
from kivymd.uix.list import OneLineListItem
from kivy.uix.screenmanager import ScreenManager, Screen
from kivymd.uix.button import MDRectangleFlatIconButton, MDFloatingActionButton
from kivy.lang import Builder
import pygame
pygame.mixer.init()
path = "C://abapp3"
class BooksScreen(Screen):
pass
class ChapterScreen(Screen):
pass
class MainApp(MDApp):
def build(self):
sm = ScreenManager()
sm.add_widget(BooksScreen(name='BooksScreen1'))
sm.add_widget(ChapterScreen(name='ChapterScreen1'))
return sm
def on_start(self):
songs = self.load_songs(path)
pygame.mixer.music.load(songs[0])
def load_songs(self, path_):
songs = []
for filename in os.listdir(path_):
if filename.endswith('.wav'):
songs.append(os.path.join(path_, filename))
self.root.ids.Chapter.add_widget(OneLineListItem(text=filename[2:],
on_release=self.play_song,
pos_hint={"center_x": 1, "center_y": 1}, ))
return songs
#staticmethod
def play_song(*args):
pygame.mixer.music.play()
print(OneLineListItem.text)
#staticmethod
def stop_song(*args):
pygame.mixer.music.stop()
print("song stopped")
MainApp().run()
.KV
ScreenManager:
Screen
BooksScreen:
ChapterScreen:
<BooksScreen>:
NavigationLayout:
ScreenManager:
Screen:
# Front / Main Screen
MDBoxLayout:
orientation: "vertical"
#Toolbar
MDToolbar:
title: "Chapters"
font_style: "Caption"
elevation: 8
left_action_items: [['menu', lambda x: nav_drawer.set_state("open")]]
Widget:
#stop/pause Button
MDBoxLayout:
orientation:"vertical"
# id: StopButton
text:"Pause"
BoxLayout:
Button:
text: 'Goto settings'
on_press:
root.manager.transition.direction = 'left'
root.manager.current = 'ChapterScreen1'
# Chapters list/ Play list
MDScreen
MDBoxLayout:
orientation: "vertical"
MDList
id: Chapter
#Options menu
MDNavigationDrawer:
id: nav_drawer
MDBoxLayout:
orientation: "vertical"
padding: "8dp"
spacing: "8dp"
ScrollView:
# Options Menu Options
MDList:
MDRectangleFlatIconButton:
on_press:
root.ids.nav_drawer.set_state("close")
pos_hint: {"center_x": .5, "center_y": .5}
icon: 'arrow-left'
line_color: 0, 0, 0, 0
OneLineIconListItem:
text: "Options"
font_style: "Caption"
#size_hint_y: None
#height: self.texture_size[1]
# Options Menu- About
OneLineIconListItem:
text: "About"
font_style: "Caption"
# size_hint_y: None
#height: self.texture_size[1]
# Options Menu Storage
OneLineIconListItem
text: 'Storage'
font_style: "Caption"
#IconLeftWidget
#icon: 'tools'
# Options Menu Toolbox
OneLineIconListItem:
text: 'Choose Voice'
font_style: "Caption"
#IconLeftWidget:
# icon: 'toolbox'
# Options Menu About
OneLineIconListItem:
text: 'About'
font_style: "Caption"
# IconLeftWidget:
# icon: 'toolbox-outline'
<ChapterScreen>:
BoxLayout:
Button:
text: 'Back to menu'
on_press:
root.manager.transition.direction = 'right'
root.manager.current = 'BooksScreen1'
The line:
self.root.ids.Chapter.add_widget(OneLineListItem(text=filename[2:],
on_release=self.play_song,
pos_hint={"center_x": 1, "center_y": 1}, ))
is trying to reference the Chapter id as if it were a member of the ScreenManager (root) ids, but it is not. It is a member of the ids of the BookScreen. You can fix that error by referencing the BookScreen instance in the problem line using the get_screen() method of ScreenManager:
self.root.get_screen('BooksScreen1').ids.Chapter.add_widget(OneLineListItem(text=filename[2:],
on_release=self.play_song,
pos_hint={"center_x": 1, "center_y": 1}, ))
Related
I am developing an app in KivyMD for Python and I'm having trouble implementing a single MDTopAppBar for multiple screens.
Here's my current code:
from kivymd.app import MDApp
from kivy.lang import Builder
from kivymd.uix.screenmanager import MDScreenManager
from kivymd.uix.screen import MDScreen
c = '''
<BuildApp>:
MDNavigationLayout:
MDScreenManager:
id: screener
FirstScreen:
SecondScreen:
MDNavigationDrawer:
id: nav_drawer
radius: (0, 16, 16, 0)
MDNavigationDrawerMenu:
MDNavigationDrawerItem:
icon: "android"
text: "Phone"
on_press: screener.current = "page2"
MDNavigationDrawerItem:
icon: "home"
text: "Home"
on_press: screener.current = "page1"
<FirstScreen>:
name: "page1"
MDBoxLayout:
orientation: 'vertical'
pos_hint: {"top": 1}
MDTopAppBar:
title: "Title"
elevation: 4
pos_hint: {"top": 1}
left_action_items: [["menu", lambda x: app.root.ids.nav_drawer.set_state("open")]]
MDFloatingActionButton:
icon: "home"
md_bg_color: app.theme_cls.primary_color
pos_hint: {"center_x":.5}
Widget:
<SecondScreen>:
name: "page2"
MDBoxLayout:
orientation: 'vertical'
pos_hint: {"top": 1}
MDTopAppBar:
title: "Title"
elevation: 4
pos_hint: {"top": 1}
left_action_items: [["menu", lambda x: app.root.ids.nav_drawer.set_state("open")]]
ScrollView:
MDList:
id: "stuffs"
OneLineListItem:
text: "Hi"
'''
class FirstScreen(MDScreen):
pass
class SecondScreen(MDScreen):
pass
sm= MDScreenManager()
sm.add_widget(FirstScreen(name="page1"))
class BuildApp(MDScreen):
pass
class DemoApp(MDApp):
def build(self):
global root_app
# self.theme_cls.theme_style = "Light"
self.theme_cls.primary_palette = "Yellow"
Builder.load_string(c)
root_app=BuildApp()
return root_app
DemoApp().run()
Since I can't accomplish the task, I manually coded a new MDTopAppBar for each MDScreen - It sucks, I know - but it's the only way I can implement my ideas given my limited knowledge of KivyMD. I hope you guys can help me. Thanks.
I followed the steps in KivyMD documentation to create a NavigationDrawer, so, I created it and everything work correctely, but the problem is to return to the first screen. I want to go back to the first screen (the Screen with name: 'main') when I click in the arrow-left in the MDToolbar, but nothing that I did worked.
KV File:
<ItemDrawer>:
theme_text_color: 'Custom'
on_release: self.parent.set_color_item(self)
IconLeftWidget:
id: icon
icon: root.icon
theme_text_color: 'Custom'
text_color: root.text_color
<ContentNavigationDrawer>:
orientation: 'vertical'
padding: '8dp'
spacing: '8dp'
AnchorLayout:
anchor_x: 'left'
size_hint_y: .3
ScrollView:
MDList:
OneLineIconListItem:
text: 'Reminders'
on_press:
root.nav_drawer.set_state('close')
root.screen_manager.current = 'RemindersWindow'
IconLeftWidget:
icon: 'bookmark-outline'
OneLineIconListItem:
text: 'To Do'
on_press:
root.nav_drawer.set_state('close')
root.screen_manager.current = 'ToDoWindow'
IconLeftWidget:
icon: 'check-outline'
OneLineIconListItem:
text: 'Settings'
on_press:
root.nav_drawer.set_state('close')
root.screen_manager.current = 'SettingsWindow'
IconLeftWidget:
icon: 'cog-outline'
OneLineIconListItem:
text: 'About'
on_press:
root.nav_drawer.set_state('close')
root.screen_manager.current = 'AboutWindow'
IconLeftWidget:
icon: 'information-outline'
Screen:
MDNavigationLayout:
ScreenManager:
id: screen_manager
Screen:
name: 'main'
MDToolbar:
title: 'Remindy'
elevation: 10
pos_hint: {'top': 1}
left_action_items: [["menu", lambda x: nav_drawer.set_state('open')]]
MainScreen:
Screen:
name: 'SettingsWindow'
FloatLayout:
orientation: 'vertical'
MDToolbar:
title: 'Settings'
elevation: 10
pos_hint: {'top': 1}
left_action_items: [["arrow-left", lambda x: x]]
OneLineIconListItem:
text: 'Themes'
pos_hint: {'center_x': .5, 'y': .8}
on_release: app.picker_theme()
IconLeftWidget
icon: 'palette-outline'
OneLineIconListItem:
text: 'Language'
pos_hint: {'center_x': .5, 'y': .7}
on_release:
IconLeftWidget:
icon: 'earth'
Screen:
name: 'RemindersWindow'
FloatLayout:
orientation: 'vertical'
MDToolbar:
elevation: 10
pos_hint: {'top': 1}
left_action_items: [["arrow-left", lambda x: x]]
MDLabel:
text: 'My Reminders'
halign: 'center'
Screen:
name: 'AboutWindow'
FloatLayout:
orientation: 'vertical'
MDToolbar:
elevation: 10
pos_hint: {'top': 1}
left_action_items: [["arrow-left", lambda x: x]]
MDLabel:
text: 'About'
halign: 'center'
Screen:
name: 'ToDoWindow'
FloatLayout:
orientation: 'vertical'
MDToolbar:
elevation: 10
pos_hint: {'top': 1}
left_action_items: [["arrow-left", lambda x: x]]
MDLabel:
text: 'To-Do'
halign: 'center'
MDNavigationDrawer:
id: nav_drawer
ContentNavigationDrawer:
screen_manager: screen_manager
nav_drawer: nav_drawer
<MainScreen#FloatLayout>:
name: 'MainScreen'
FloatLayout:
orientation: 'vertical'
MDFloatingActionButton:
icon: 'pencil-plus-outline'
pos_hint: {'x': .8, 'y': .1/2}
on_release: root.datacard()
<CardScreen>:
FloatLayout:
orientation: 'vertical'
MDCard:
size_hint: .8, .1
MDLabel:
id: base_label
text: 'New Reminder'
<CardBox>:
orientation: 'vertical'
size_hint: .7, .5
pos_hint: {'center_x': .5, 'center_y': .5}
MDBoxLayout:
size_hint_y: .5
md_bg_color: app.theme_cls.primary_color
MDLabel:
text: 'Add a Reminder'
font_style: 'H6'
theme_text_color: 'Custom'
text_color: 1, 1, 1, 1
halign: 'center'
MDIconButton:
icon: 'window-close'
on_release: root.closecard()
MDFloatLayout:
MDTextField:
id: title_id
hint_text: 'Title'
max_text_length: 15
required: True
helper_text_mode: 'on_error'
helper_text: 'This Field is Required.'
size_hint_x: .8
pos_hint: {'center_x': .5, 'y': .1}
MDFloatLayout:
orientation: 'horizontal'
MDRectangleFlatIconButton:
icon: 'clock-time-four-outline'
text: 'Hour'
pos_hint: {'x': .1, 'y': .3}
on_release: root.picker_hora()
MDRectangleFlatIconButton:
icon: 'calendar-outline'
text: 'Date'
pos_hint: {'x': .6, 'y': .3}
on_release: root.picker_data()
MDFloatLayout:
MDRectangleFlatButton:
text: 'Add'
size_hint_x: .8
pos_hint: {'center_x': .5, 'y': .2}
Python File:
import pickle
from kivy.app import App
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivymd.uix.toolbar import MDToolbar
from kivy.properties import ObjectProperty
from kivymd.uix.list import StringProperty
from kivymd.theming import ThemableBehavior
from kivymd.uix.list import OneLineIconListItem
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.floatlayout import FloatLayout
from kivymd.uix.picker import MDThemePicker
from kivymd.uix.picker import MDTimePicker
from kivymd.uix.picker import MDDatePicker
from kivymd.uix.list import MDList
from kivymd.uix.card import MDCard
class ItemDrawer(OneLineIconListItem):
icon = StringProperty()
class ContentNavigationDrawer(BoxLayout):
screen_manager = ObjectProperty()
nav_drawer = ObjectProperty()
class MainScreen(FloatLayout):
def datacard(self):
self.add_widget(CardBox())
class CardBox(MDCard):
def closecard(self):
self.parent.remove_widget(self)
def picker_hora(self):
time_dialog = MDTimePicker()
time_dialog.open()
def picker_data(self):
date_dialog = MDDatePicker()
date_dialog.open()
def new_card(self):
# Remove and Create a New Card
self.parent.remove_widget(self)
title = self.ids.title_input.text
self.add_widget(CardScreen())
App.get_running_app().root.ids.base_label.text = title
class CardScreen(FloatLayout):
pass
class ReminderApp(MDApp):
Window.size = (400, 600)
def picker_theme(self):
theme_dialog = MDThemePicker()
theme_dialog.open()
def build(self):
return Builder.load_string(KV)
ReminderApp().run()
You need to trigger some action from the button associated to MDToolbar to switch to another screen.
For simple usage you can use the default function setattr as,
left_action_items: [["arrow-left", lambda *args : setattr(screen_manager, "current", "main")]]
Or for advanced usage you can refer to a function from some relevant class say, the App's subclass, as,
left_action_items: [["arrow-left", app.go_home]]
Now in that method,
def go_home(self, *args):
# Access the `ScreenManager` and change the screen.
self.root.ids.screen_manager.current = "main"
# Some other actions.
Also as a side note, you should change the line <MainScreen#FloatLayout> in kvlang with just <MainScreen> as you already defined it in .py. Otherwise a warning may be raised in log.
I am using an MDSelectionList inside a tab with an MDNavigationRail to switch between screens, however, when I try to customize the MDSelectionList, none of the visual changes apply. I thought that maybe it is a problem with the widget itself but then I separated it and the property changes worked. How can I make the changes apply to the selection list? (I am using kivymd 0.104.2.dev0 from the master branch)
My Code:
from kivy.config import Config
Config.set('graphics', 'width', '850')
Config.set('graphics', 'height', '530')
Config.set('graphics', 'minimum_width', '850')
Config.set('graphics', 'minimum_height', '530')
from kivy.lang import Builder
from kivymd.uix.card import MDCard
from kivymd.uix.tab import MDTabsBase
from kivymd.app import MDApp
class SettingsTab(MDCard, MDTabsBase):
pass
class Example(MDApp):
def __init__(self, **kwargs):
super(Example, self).__init__(**kwargs)
self.kv = Builder.load_string('''
#:kivy 2.0.0
<SettingsTab>:
orientation: "vertical"
size_hint: .95, .95
pos_hint: {"center_x": .5, "center_y": .5}
border_radius: 5
radius: [5]
elevation: 20
BoxLayout:
MDNavigationRail:
color_active: app.theme_cls.primary_color
MDNavigationRailItem:
icon: "list-status"
on_release:
screens.current = "downloads_screen"
MDNavigationRailItem:
icon: "cog"
on_release:
screens.current = "settings"
MDNavigationRailItem:
icon: "information"
on_release:
screens.current = "activity_log"
ScreenManager:
id: screens
Screen:
name: "downloads_screen"
Screen:
name: "activity_log"
Screen:
name: "settings"
MDTabs:
SettingsTab:
title: "DOWNLOAD"
MDSelectionList:
overlay_color: 1, 0, 0, .5
icon_bg_color: 0, 0, 0, 0
icon_check_color: 0, 0, 0, 0
OneLineIconListItem:
text: "Just me!"
IconLeftWidget:
icon: "circle-outline"
pos_hint: {"center_x": .5, "center_y": .5}
OneLineIconListItem:
text: "Just me!"
IconLeftWidget:
icon: "circle-outline"
OneLineIconListItem:
text: "Just me!"
IconLeftWidget:
icon: "circle-outline"
OneLineIconListItem:
text: "Just me!"
IconLeftWidget:
icon: "circle-outline"
SettingsTab:
title: "COLOR"
SettingsTab:
title: "INFO"''')
def build(self):
self.theme_cls.theme_style = "Dark"
self.theme_cls.primary_palette = "Blue"
self.theme_cls.accent_palette = "Teal"
return self.kv
if __name__ == '__main__':
Example().run()
Try something like this.
from kivy.lang import Builder
from kivymd.uix.card import MDCard
from kivymd.uix.tab import MDTabsBase
from kivymd.app import MDApp
kv = ("""
<Check#ILeftBodyTouch+MDCheckbox>:
group: 'group'
size_hint: None, None
size: dp(48), dp(48)
<SettingsTab>:
orientation: "vertical"
size_hint: .95, .95
pos_hint: {"center_x": .5, "center_y": .5}
border_radius: 5
radius: [5,]
elevation: 20
BoxLayout:
MDNavigationRail:
color_active: app.theme_cls.primary_color
MDNavigationRailItem:
icon: "cog"
on_release:
screens.current = "settings"
ScreenManager:
id: screens
Screen:
name: "settings"
MDTabs:
SettingsTab:
title: "DOWNLOAD"
MDList:
spacing: 10
OneLineAvatarIconListItem:
text: "Just me!"
Check:
OneLineAvatarIconListItem:
text: "Just me!"
Check:
OneLineAvatarIconListItem:
text: "Just me!"
Check:
""")
class SettingsTab(MDCard, MDTabsBase):
pass
class Example(MDApp):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.kv = Builder.load_string(kv)
def build(self):
return self.kv
if __name__ == '__main__':
Example().run()
I think this problem is easy to solve, but i dont have experience enough to do this.
So, I want to reference the input text (MDTextField on kv file) for the variable "name" that is inside the press() function, so that I can write inside the popup.
I'm learning kivymd for a college project, so, discount the errors and unnecessary informations :/
Here is my kv file
Screen:
id: screen1
NavigationLayout:
id: navigation
ScreenManager:
id: screen_manager
Screen:
id: fact
name: 'fact'
BoxLayout:
orientation: 'vertical'
MDToolbar:
title: "Menu"
elevation: 10
left_action_items: [['menu', lambda x: nav_drawer.set_state()]]
Widget:
MDLabel:
text: "Fact Checker"
font_size: 56
font_name: "MontserratBold"
pos_hint: {'center_x': 0.75, 'center_y': 0.7}
theme_text_color: "Custom"
text_color: (53/255, 183/255, 1, 1)
MDTextField:
id: input_box
hint_text: "Type here"
font_size: 18
pos_hint: {'center_x': 0.5, 'center_y': 0.45}
size_hint_x: None
width: 500
multiline: True
helper_text: "Type the title of the news"
helper_text_mode: "on_focus"
theme_text_color: "Custom"
text_color: (53/255, 183/255, 1, 1)
line_color_normal: 1, 1, 1, 1
MDRectangleFlatButton:
text: "Check"
pos_hint: {'center_x': 0.5, 'center_y': 0.25}
theme_text_color: "Custom"
text_color: (1, 1, 1, 1)
on_press: app.press()
MDLabel:
markup: True
text: "<Developed by: [color=#cfd0d1]Caio Barreto and Gabriel Queiroz[/color]>"
font_name: "Montserrat"
theme_text_color: "Custom"
text_color: (53/255, 183/255, 1, 0.5)
pos_hint: {'center_x': 0.74, 'center_y': 0.1}
Screen:
name: 'discord'
BoxLayout:
orientation: 'vertical'
MDToolbar:
title: "Menu"
elevation: 10
left_action_items: [['menu', lambda x: nav_drawer.set_state()]]
Widget:
MDLabel:
text: 'teste1'
Screen:
name: 'add'
BoxLayout:
orientation: 'vertical'
MDToolbar:
title: "Menu"
elevation: 10
left_action_items: [['menu', lambda x: nav_drawer.set_state()]]
Widget:
MDLabel:
text: 'teste2'
MDNavigationDrawer:
id: nav_drawer
ContentNavigationDrawer:
ScrollView:
DrawerList:
id: md_list
MDList:
OneLineIconListItem:
text: "Menu"
on_press: screen_manager.current = "fact"
IconLeftWidget:
icon: "home"
OneLineIconListItem:
text: "Discord"
on_press: screen_manager.current = "discord"
IconLeftWidget:
icon: "discord"
OneLineIconListItem:
text: "Add more news"
on_press: screen_manager.current = "add"
IconLeftWidget:
icon: "circle-edit-outline"
Here is my python code:
from kivymd.app import MDApp
from kivy.lang.builder import Builder
from kivymd.uix.dialog import MDDialog
from kivymd.uix.textfield import MDTextField
from kivymd.uix.button import MDRectangleFlatButton, MDFlatButton
from kivymd.uix.navigationdrawer import NavigationLayout
from kivymd.uix.list import MDList
from kivymd.uix.boxlayout import BoxLayout
from kivymd.theming import ThemableBehavior
from kivy.core.text import LabelBase
from kivy.uix.widget import Widget
from helper import username_input
from kivymd.uix.screen import Screen
LabelBase.register(name="MontserratBold", fn_regular="font/Montserrat-Bold.ttf")
LabelBase.register(name="Montserrat", fn_regular="font/Montserrat-Medium.ttf")
class FactCheckerApp(MDApp):
class ContentNavigationDrawer(BoxLayout):
pass
class DrawerList(ThemableBehavior, MDList):
pass
def build(self):
self.file = Builder.load_file('projeto.kv')
self.theme_cls.theme_style = "Dark"
self.theme_cls.primary_palette = "LightBlue"
print(self.file.Screen.ids.)
return self.file
def press(self):
name = self.screen1.navigation.screen_manager.fact.input_box.text
close_button = MDFlatButton(text='Close', on_release=self.close_dialog)
self.dialog = MDDialog(title='Answer', text=name, size_hint=(0.5, 1), buttons=[close_button])
self.dialog.open()
def close_dialog(self, obj):
self.dialog.dismiss()
if __name__ == '__main__':
FactCheckerApp().run()
To access the MDTextField, you can just reference it through its id, which is defined in the widget that is the root of the kv rule where the id is defined (in this case, in the Screen). Try changing:
name = self.screen1.navigation.screen_manager.fact.input_box.text
to:
name = self.root.ids.input_box.text
in the press() method.
I am using KivyMD and would like to refrash data in the the secound screen using the "on_pre_enter" method.
I am trying to access a label id from screen class "on_pre_enter" method with out success.
I am able to access the label id from the "MainApp" class but unable to access it from the "Second_Screen" class.
MainApp.py
from kivy.lang import Builder
from kivymd.app import MDApp
from kivy.uix.screenmanager import ScreenManager, Screen
class MainApp(MDApp):
def __init__(self, **kwargs):
self.title = "My Material Application"
self.theme_cls.primary_palette = "Blue"
super().__init__(**kwargs)
def on_start(self):
self.root.ids.main_screen_label.text = "Main Screen Updated"
def build(self):
self.root = Builder.load_file("app.kv")
class Second_Screen(Screen):
def on_pre_enter(self):
MainApp.ids.second_screen_label = "Second Screen Updated"
pass
if __name__ == "__main__":
MainApp().run()
App.kv
NavigationLayout:
MDNavigationDrawer:
NavigationDrawerSubheader:
text: "Menu:"
NavigationDrawerIconButton:
icon:'battery'
text: "Main Screen"
on_release:
screen_manager.current = "main_screen"
NavigationDrawerIconButton:
icon:'battery'
text: "Second Screen"
on_release:
screen_manager.current = "second_screen"
BoxLayout:
id: box1
orientation: 'vertical'
MDToolbar:
title: "My App"
md_bg_color: app.theme_cls.primary_color
left_action_items:
[['menu', lambda x: app.root.toggle_nav_drawer()]]
ScreenManager:
id: screen_manager
Screen:
name: "main_screen"
BoxLayout:
size_hint: .8, .8
pos_hint: {"center_x": .5, "center_y": .5}
spacing: dp(100)
orientation: 'vertical'
MDLabel:
id: main_screen_label
text: "Main Screen Default"
Second_Screen:
name: "second_screen"
FloatLayout:
id: float
size_hint: .8, .8
pos_hint: {"center_x": .5, "center_y": .5}
spacing: dp(100)
orientation: 'vertical'
MDLabel:
id: second_screen_label
text: "Second Screen Default"
I also tried using:
class Second_Screen(Screen):
def on_pre_enter(self):
self.ids.second_screen_label.text = "Second Screen Updated"
pass
After starting the i get the following error:
self.ids.second_screen_label.text = "Second Screen Updated"
File "kivy\properties.pyx", line 863, in
kivy.properties.ObservableDict.__getattr__
AttributeError: 'super' object has no attribute '__getattr__'
What is the correct way to access the id's defined in the KV file from the screen class?
Define screen layout in separate rule <MyScreen>:
<MyScreen>:
name: "my_screen"
FloatLayout:
# ...
To add this screen to ScreenManager, just write:
ScreenManager:
id: screen_manager
MyScreen:
To get access to screen widgets use
from screen class: self.ids.my_id
from app class: self.root.ids.screen_manager.get_screen("screen_name").ids.my_id
from other widgets: App.get_running_app()..root.ids.screen_manager.get_screen("screen_name").ids.my_id
So your full code will be:
main.py
from kivy.lang import Builder
from kivymd.app import MDApp
from kivy.uix.screenmanager import Screen
class MainApp(MDApp):
def __init__(self, **kwargs):
self.title = "My Material Application"
self.theme_cls.primary_palette = "Blue"
super().__init__(**kwargs)
def build(self):
self.root = Builder.load_file("app.kv")
def on_start(self):
self.root.ids.screen_manager.get_screen(
"main_screen"
).ids.main_screen_label.text = "Main Screen Updated"
class MainScreen(Screen):
pass
class SecondScreen(Screen):
def on_pre_enter(self):
self.ids.second_screen_label.text = "Second Screen Updated"
if __name__ == "__main__":
MainApp().run()
app.kv
NavigationLayout:
MDNavigationDrawer:
NavigationDrawerSubheader:
text: "Menu:"
NavigationDrawerIconButton:
icon: "battery"
text: "Main Screen"
on_release:
screen_manager.current = "main_screen"
NavigationDrawerIconButton:
icon: "battery"
text: "Second Screen"
on_release:
screen_manager.current = "second_screen"
BoxLayout:
id: box1
orientation: "vertical"
MDToolbar:
title: "My App"
md_bg_color: app.theme_cls.primary_color
left_action_items:
[["menu", lambda x: app.root.toggle_nav_drawer()]]
ScreenManager:
id: screen_manager
MainScreen:
SecondScreen:
<MainScreen>:
name: "main_screen"
BoxLayout:
size_hint: .8, .8
pos_hint: {"center_x": .5, "center_y": .5}
spacing: dp(100)
orientation: "vertical"
MDLabel:
id: main_screen_label
text: "Main Screen Default"
<SecondScreen>:
name: "second_screen"
FloatLayout:
id: float
size_hint: .8, .8
pos_hint: {"center_x": .5, "center_y": .5}
spacing: dp(100)
orientation: "vertical"
MDLabel:
id: second_screen_label
text: "Second Screen Default"