Python Kivy screen manager wiget scope

2024/10/15 23:29:54

I am trying to control a screen manager from buttons in a separate class, but I cannot figure out what to set on the button on_press: statements.

Kivy Python Nav

Kivy file:

<HeaderSection>:anchor_x: 'center'anchor_y: 'top'BoxLayout:orientation: 'horizontal'size_hint: 1, .1id: headerLabel:text: 'My App'<ContentSection>:anchor_x: 'center'anchor_y: 'center'ScreenManager:size_hint: 1, .8Screen:name: 'home'Label:text: 'First screen'Screen:name: 'second'Label:text: 'Second screen'Screen:name: 'third'Label:text: 'Third screen'<FooterSection>:anchor_x: 'center'anchor_y: 'bottom'BoxLayout:orientation: 'horizontal'size_hint: 1, .1Button:text: 'first'on_press: root.ContentSection.manager.current = 'first'Button:text: 'second'on_press: root.current = 'second'Button:text: 'third'on_press: ContentSection.ScreenManager.current = 'third'

Python file:

from kivy.app import App
from kivy.lang import Builder
Builder.load_file('MyApp.kv')
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.label import Label
from kivy.uix.image import Image# Declare sections
class HeaderSection(AnchorLayout):passclass ContentSection(AnchorLayout):def build(self):# Create the screen managersm = ScreenManager()sm.add_widget(FirstScreen(name='first'))sm.add_widget(SecondScreen(name='second'))sm.add_widget(ThirdScreen(name='third'))return smclass FooterSection(AnchorLayout):passclass MyAppApp(App):def build(self):#Create the sectionsfl = FloatLayout()hs = HeaderSection()cs = ContentSection()fs = FooterSection()fl.add_widget(hs)fl.add_widget(cs)fl.add_widget(fs)return flif __name__ == '__main__':MyAppApp().run()

I have tried various methods:

on_press: root.parent.ContentSection.ScreenManager.current = 'home'
on_press: root.parent.ContentSection.manager.current = 'home'
on_press: root.ContentSection.manager.current = 'home'

I feel like it is a scoping issue, errors say things like:

AttributeError: 'FooterSection' object has no attribute 'ContentSection'

So my app has the following hierarchy:

FloatLayoutHeaderSectionContentSectionScreenManagerFirstScreenSecondScreenThirdScreenFooterSectionButton for FirstScreenButton for SecondScreenButton for ThirdScreen

So I need to traverse up a level into FloatLayout, then drill down into ContentSection to access the screen manager.

Answer

Navigating widget trees has been a pain for me, and AFAIK you can't traverse the widget tree the way you'd like.

You can, however, simplify your widget tree, make sure everything shares the same root, and use ids.

Here's how I did it (I also moved everything to kv language):

kv

FloatLayout:AnchorLayout:anchor_x: 'center'anchor_y: 'top'Label:size_hint: 1, .1text: 'My App'AnchorLayout:anchor_x: 'center'anchor_y: 'center'ScreenManager:id: managersize_hint: 1, .8Screen:name: 'first'Label:text: 'First screen'Screen:name: 'second'Label:text: 'Second screen'Screen:name: 'third'Label:text: 'Third screen'AnchorLayout:anchor_x: 'center'anchor_y: 'bottom'BoxLayout:orientation: 'horizontal'size_hint: 1, .1Button:text: 'first'on_press: root.ids.manager.current = 'first'Button:text: 'second'on_press: root.ids.manager.current = 'second'Button:text: 'third'on_press: root.ids.manager.current = 'third'

python

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.label import Label
from kivy.uix.image import Imageclass MyAppApp(App):def build(self):return Builder.load_file('MyApp.kv')if __name__ == '__main__':MyAppApp().run()
https://en.xdnf.cn/q/117779.html

Related Q&A

How do the async and await keywords work, exactly? Whats at the end of the await chain?

I have this code:async def foo(x):yield xyield x + 1async def intermediary(y):await foo(y)def bar():c = intermediary(5)What do I put in bar to get the 5 and the 6 out of c?Im asking because the asynci…

Serial port writing style

I am using two libraries to connect with a port, and two of them uses different styles in writing these commands. I want to understand the difference because I want to use the second one, but it result…

matplotlib plot to fill figure only with data points, no borders, labels, axes,

I am after an extreme form of matplotlibs tight layout. I would like the data points to fill the figure from edge to edge without leaving any borders and without titles, axes, ticks, labels or any othe…

Chromedriver: FileNotFoundError: [WinError 2] The system cannot find the file specified Error

Have looked for an answer, but couldnt find anything. It seems insistent on saying it cant find the file specified and then checks PATH, but cant see it even then :/ Ive put the directory in PATH: http…

Python - mutable default arguments to functions

I was going through https://docs.python.org/3.5/tutorial/controlflow.html#default-argument-values. I modified the example there a little bit as below:x = [4,5] def f(a, L=x):L.append(a)return Lx = [8,9…

Python: remove duplicate items from a list while iterating

I have a list named results, I want to get rid of the duplicate items in the list, the expected result and my results does not match, I checked my code but cannot find what is the problem, what happene…

Python - SciPy Kernal Estimation Example - Density 1

Im currently working through this SciPy example on Kernal Estimation. In particular, the one labelled "Univariate estimation". As opposed to creating random data, I am using asset returns. …

PyQt QFileDialog custom proxy filter not working

This working code brings up a QFileDialog prompting the user to select a .csv file:def load(self,fileName=None):if not fileName:fileName=fileDialog.getOpenFileName(caption="Load Existing Radio Log…

If I have Pandas installed correctly, why wont my import statement recognize it?

Im working on a project to play around with a csv file, however, I cant get pandas to work. Everything I have researched so far has just told me to make sure that pandas is installed. Using pip I have …

Python Issues with a Class

I am having issues with my below class. I keep getting the below traceback, butI am not sure were I am going wrong. I am expecting to see a dictionary with photo tags. Any help would be great. Tracebac…