Reference a input box id on kivy screen - python

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.

Related

How can I use one MDTopAppBar across multiple Screens in MDScreenManager?

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.

How to go back to the previous screen from left_action_items of MDToolbar in KivyMD?

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.

Toolbar text does not change in kivyMD and text goes beyond the boundaries

from kivymd.app import MDApp
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import ObjectProperty
class ContentNavigationDrawer(BoxLayout):
"""This class manage the navigation drawer contents"""
screen_manager = ObjectProperty()
nav_drawer = ObjectProperty()
class MyApp(MDApp):
def build(self):
"""Return the main kivy file and set themes """
self.theme_cls.theme_style = "Dark"
self.theme_cls.primary_palette = 'BlueGray'
self.theme_cls.accent_palette = "Teal"
return Builder.load_file("main.kv")
MyApp().run()
and the kv file
<ContentNavigationDrawer>:
MDBoxLayout:
orientation: "vertical"
spacing: dp("8")
padding: dp("8")
ScrollView:
MDList:
OneLineIconListItem:
text: "hexagon"
on_press:
root.nav_drawer.set_state("close")
root.screen_manager.current = "mainScreen"
IconLeftWidget:
icon: 'hexagon'
MDScreen:
MDToolbar:
id: toolbar
title: "Hexagon"
md_bg_color: app.theme_cls.primary_color
specific_text_color: 1, 1, 1, 1
pos_hint: {"top": 1}
elevation: 9
icon: 'account-circle'
left_action_items: [["menu", lambda x: nav_drawer.set_state("open")]]
MDNavigationLayout:
x: toolbar.height
ScreenManager:
id: screen_manager
MDScreen:
name: "mainScreen"
BoxLayout:
orientation: 'vertical'
size: root.width, root.height
ScrollView:
do_scroll_x: True
do_scroll_y: True
size_hint: (1, .85)
bar_width: 10
bar_color: (1, 0, 0 ,1)
scroll_type: ["bars", "content"]
pos_hint: {'top': 1.0 - toolbar.height/float(root.height)}
GridLayout:
id: labels_layout
size_hint_y: None
height:self.minimum_height
size_hint_x: None
width: self.minimum_width
cols: 1
spacing: "5dp"
padding: "5dp"
MDLabel:
id: big_text_label
text: "asldklsa\nasdsaf\nssss\n"
width: self.texture_size[1]
height: self.texture_size[1]
MDNavigationDrawer:
id: nav_drawer
ContentNavigationDrawer:
screen_manager: screen_manager
nav_drawer: nav_drawer
test_screen_shot
I want to change the color of the toolbar I tried almost everything to do it
like md_bg_color: app.theme_cls.primary_color and md_bg_color: .2, .2, .2, 1
And the text goes beyond the boundaries even of the app if i add some widgets to get back
text to its area the it goes under the toolbar
Using:
Python 3.9, dev kivyMD 2.0, editor pycharm
Use:
from kivymd.app import MDApp
from kivy.lang import Builder
KV = """
<ContentNavigationDrawer>:
MDBoxLayout:
orientation: "vertical"
spacing: dp("8")
padding: dp("8")
ScrollView:
MDList:
OneLineIconListItem:
divider: None
text: "hexagon"
on_press:
app.root.ids.nav_drawer.set_state("toggle")
#root.screen_manager.current = "mainScreen"
IconLeftWidget:
icon: 'account'
## BoxLayout:
## canvas.before:
## Color:
## rgba: [1,.3,0,1]
## Line:
## width: dp(1)
## rounded_rectangle:
## (self.x, self.y, self.width-dp(20), dp(43),\
## dp(12),dp(12),dp(12),dp(12),\
## dp(50))
OneLineIconListItem:
divider: None
text: "hexagon"
on_press:
app.root.ids.nav_drawer.set_state("toggle")
#root.screen_manager.current = "mainScreen"
IconLeftWidget:
icon: 'hexagon'
OneLineIconListItem:
divider: None
text: "Edit"
on_press:
app.root.ids.nav_drawer.set_state("toggle")
#root.screen_manager.current = "mainScreen"
IconLeftWidget:
icon: 'pencil'
OneLineIconListItem:
divider: None
text: "Home"
on_press:
app.root.ids.nav_drawer.set_state("toggle")
#root.screen_manager.current = "mainScreen"
IconLeftWidget:
icon: 'home'
OneLineIconListItem:
divider: None
text: "Likes"
on_press:
app.root.ids.nav_drawer.set_state("toggle")
#root.screen_manager.current = "mainScreen"
IconLeftWidget:
icon: 'star'
OneLineIconListItem:
divider: None
text: "hexagon"
on_press:
app.root.ids.nav_drawer.set_state("toggle")
#root.screen_manager.current = "mainScreen"
IconLeftWidget:
icon: 'hexagon'
OneLineIconListItem:
divider: None
text: "Search"
on_press:
app.root.ids.nav_drawer.set_state("toggle")
#root.screen_manager.current = "mainScreen"
IconLeftWidget:
icon: 'magnify'
Screen:
MDToolbar:
id: toolbar
pos_hint: {"top": 1}
title: "Hexagon"
md_bg_color: [1,0,0,1]
specific_text_color: [1, 1, 1, 1]
elevation: 0
left_action_items: [["menu", lambda x: nav_drawer.set_state("toggle")]]
right_action_items: [["account-circle", lambda x: print(222)]]
ScreenManager:
id: screen_manager
MDScreen:
name: "mainScreen"
FloatLayout:
BoxLayout:
id: m5
pos_hint: {"center_x": .5, "center_y": .38} #this will change if you change this Window.size = (330, 500)
orientation: "vertical"
ScrollView:
do_scroll_x: False #True
do_scroll_y: True
#size_hint: (1, .85)
bar_width: 10
bar_color: (1, 0, 0 ,1)
scroll_type: ["bars", "content"]
pos_hint: {'top': 1.0 - toolbar.height/float(root.height)}
GridLayout:
id: labels_layout
size_hint_y: None
height:self.minimum_height
size_hint_x: 1
#width: self.minimum_width
cols: 1
spacing: "5dp"
padding: dp(20)
MDLabel:
id: big_text_label
text: "\\n\\n\\n\\n\\n\\nWelcome to this New App.\\nYou will get a lot of benefits.\\n\\njbsidis recommendations are good so we can design in different ways."
MDNavigationDrawer:
id: nav_drawer
ContentNavigationDrawer:
screen_manager: screen_manager
"""
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
class ContentNavigationDrawer(BoxLayout):
"""This class manage the navigation drawer contents"""
screen_manager = ObjectProperty()
#nav_drawer = ObjectProperty()
class WeatherApp(MDApp):
def __init__(self, **kwargs):
super().__init__(**kwargs)
pass
def build(self):
self.screen = Builder.load_string(KV)
return self.screen
WeatherApp().run()
Pictures:

MDSelectionList properties cannot be modified

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()

Multiple screens but self.root.ids retuns an error

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}, ))

Categories