Search code examples
pythonkivy

How can I reach a spesific member of a kivy screen inside another class?


I'm quite new to python. I'm trying to enable a button of a kivy screen inside a popup but I failed to adress the related screen (and therefore button of that screen) as I am outside of its class. Can you show me how I can adress it properly ? Below I try to simulate the issue as plain as possible. (If you see any other areas of development, feel free to adress.) Thanks in advance...

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.uix.screenmanager import ScreenManager, Screen

popupWindow = ""

class S_Mananager(ScreenManager):
    pass

class S_Primary(Screen):
    
    def show_pop_up(self):
        global popupWindow
        popupWindow = Popup( 
            content     = pup_Pass(), 
            size_hint   = (None,None), 
            size        = (250, 300)
            )
        popupWindow.open()

class pup_Pass(BoxLayout):

    def btn_OK(self):
        global popupWindow
        popupWindow.dismiss()
        S_Mananager.get_screen("scr_primary").ids.btn_enable_me.disabled = False

class S_Secondary(Screen):
    pass

class Screens(App):
    def build(self):
        pass

if __name__ == '__main__':
    Screens().run()

KV File:

<pup_Pass>:

    orientation:    "vertical"
    size:           root.width, root.height
    Label:
        text:       "Label"
    Button:
        text:       "OK"
        on_release: root.btn_OK()

S_Mananager:

    S_Primary:
    S_Secondary:


<S_Primary>:
    
    name:   "win_Main"

    BoxLayout:
        id:             "scr_primary"
        orientation:    "vertical"
        size:           root.width, root.height
        Label:
            text:           'Label'
        Button:
            text:           'Button'
            on_release:     root.show_pop_up()
        Button:
            id:             "btn_enable_me"
            text:           'Enable Me by Popup !'
            on_release:     root.show_pop_up()
            disabled:       True

<S_Secondary>:

Solution

  • Two problems:

    1. You are trying to call get_screen() as though it were a class method, but it is an instance method. You need to call get_screen() through an instance of ScreenManager.
    2. You should not use strings for ids.

    The fix is to first change the id for the Button:

        Button:
            id:             btn_enable_me  # not a string
    

    Then modify your python to use the instance of ScreenManager in your GUI:

    def btn_OK(self):
        global popupWindow
        popupWindow.dismiss()
        App.get_running_app().root.get_screen("win_Main").ids.btn_enable_me.disabled = False
    

    Note that get_screen() requires the name of a Screen (which should be a string), not the id.