简体   繁体   中英

How do I access ScreenManager commands through the main.py file?

So I'm making an app using Kivy. One of my screens have buttons that are indeterminate in number so they are added through the main.py file using a for loop. My code goes something like this:

class CategWin(Screen):
    @mainthread
    def on_enter(self, **kwargs):
        for i in range(10):
            button = Button(text="B_" + str(i),
                            color=(1, 1, 1, 1),
                            background_normal="button1.png",
                            background_down="button2.png")
            self.ids.menu.add_widget(button)

class ChannelWin(Screen):
    ***some code***
    pass

class WindowManager(ScreenManager):
    pass


kv = Builder.load_file("my.kv")

class MyMainApp(App):
    def build(self):
        return kv

if __name__ == "__main__":
    MyMainApp().run()

The first class has the mentioned function. In a kv file, you can use

on_release:
    app.root.current = "screen_name"
    root.manager.transition.direction = "right"

to assign switch screen commands but how do you do it through the main.py file?

I also tried the switch_to() function mentioned in the documentation but it returns this error.

##Code:
button.bind(on_press=WindowManager.switch_to(ChannelWin))
TypeError: switch_to() missing 1 required positional argument: 'screen'

I'm pretty new to kivy so I'm lost. I also can't find any solutions online.

You can do something like this:

class CategWin(Screen):
    @mainthread
    def on_enter(self, **kwargs):
        for i in range(10):
            button = Button(text="B_" + str(i),
                            color=(1, 1, 1, 1),
                            background_normal="button1.png",
                            background_down="button2.png")
            button.bind(on_press=self.go_to_Channelwin)
            self.ids.menu.add_widget(button)

    def go_to_Channelwin(self, pressed_button):
        self.manager.current = "ChannelWin_screen_name"

Where ChannelWin_screen_name is replaced by whatever name you have assigned to the ChannelWin instance.

在您的回调定义中,您可以使用带有WindowManager.current属性的 python 内置函数,而不是使用WindowManager.switch_to函数。

setattr(WindowManager,'current','screen_name')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM