Interaction between Kivy widgets in Python

后端 未结 1 1315
时光取名叫无心
时光取名叫无心 2020-12-02 02:21

I\'m doing a proyect using kivy but i have a problem with the checkboxes. At first I\'m trying to do the program like python coding (I know it is\'nt clean, but I understand

相关标签:
1条回答
  • 2020-12-02 02:50

    What you want is accessing variables in other classes. Sometimes this can be annoying and you can do it either hard way with all __init__() and stuff, or... a simplier way comes along: it's get_running_app().

    You can create a dictionary or something else, where you can store any value your other classes need to access. It's similar to using globals and it costs you less lines of code. For example in your case you could use a dictionary(or nested dictionaries, json, ...) to store for example 'checkboxes':'<names of checked ones>' and in each init you can loop over these values to make checkboxes active

    Basically all you need is a = App.get_running_app() somewhere and something to access in main - App - class.

    Example:

    from kivy.app import App
    from kivy.lang import Builder
    from kivy.uix.screenmanager import ScreenManager, Screen
    Builder.load_string('''
    <Root>:
        MainScreen:
            name: 'main'
        AnotherScreen:
            name: 'another'
    <MainScreen>:
        BoxLayout:
            Button:
                text: 'next screen'
                on_release: root.parent.current='another'
            Button:
                text: 'ping!'
                on_release: root.ping()
    <AnotherScreen>:
        BoxLayout:
            Button:
                text: 'previous screen'
                on_release: root.parent.current='main'
            Button:
                text: 'ping!'
                on_release: root.ping()
    ''')
    
    class MainScreen(Screen):
        def __init__(self, **kw):
            super(MainScreen, self).__init__(**kw)
            self.a = App.get_running_app()
        def ping(self):
            print self.a.big_dict['hi']
    
    class AnotherScreen(Screen):
        def ping(self):
            b = App.get_running_app()
            print b.big_dict['hi']
    
    class Root(ScreenManager):
        pass
    class SimpleKivy(App):
        big_dict={'hi':'hi there!'}
        def build(self):
            return Root()
    SimpleKivy().run()
    

    You can see there's no need to call __init__(), no need to write more lines of code if you really don't need to.

    0 讨论(0)
提交回复
热议问题