在Kivy中制作(续)选项屏幕

时间:2018-10-22 00:33:56

标签: python popup kivy

我正在努力获得一个在所有屏幕上都相同的选项菜单。选项菜单是带有一些选项的弹出窗口。调用弹出窗口时,它不会保存输入。当“切换”按钮更改为非活动状态时,在用户关闭并重新打开弹出窗口后,它会默认恢复为活动状态。

如何保存用户的输入?

from kivy.app import App
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.switch import Switch

Builder.load_string('''

<OptionMenu@Button>:
    text: "Option Menu"
    size_hint_y: .3
    on_press:
        app.option_menu_function()

<BoxLayout@BoxLayout>:
    orientation: "vertical"

<HomeScreen>:
    BoxLayout:
        OptionMenu:
        Label:
            text: "Home Screen"
        Button:
            text: "Next Screen >"
            on_release:
                app.root.current = "screen1"
<Screen1>:
    BoxLayout:
        OptionMenu:
        Label:
            text: "Screen 2"
        Button:
            text: "Next Screen >"
            on_release:
                app.root.current = "homescreen"
<SM>:
    name: "sm"
    id: sm
    HomeScreen:
        name: "homescreen"
        id: hs
    Screen1:
        name: "screen1"
        id: s1
''')

class HomeScreen(Screen):
    pass
class Screen1(Screen):
    pass
class SM(ScreenManager):
    pass

class MyApp(App):

    def build(self):
        global sm
        sm = SM()
        return sm

    def option_menu_function(self):
        box = BoxLayout(orientation = "horizontal")
        switch = Switch(active = True)
        popup = Popup(content = box, auto_dismiss = True, size_hint = (None, None), size = (Window.width/1.5, Window.width/1.5))
        box.add_widget(switch)
        popup.open()

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

1 个答案:

答案 0 :(得分:1)

之所以不保存小部件的状态,是因为您随时都在创建一个新的小部件,因此解决方案是重用。另一方面,在必须使用全局变量的情况下,避免使用全局变量,因为它们会引起问题。考虑到上述情况,解决方案如下:

class MyApp(App):
    def build(self):
        box = BoxLayout(orientation = "horizontal")
        box.add_widget(Switch(active = True))
        # a single popup is created
        self.popup = Popup(content = box, auto_dismiss = True, size_hint = (None, None), size = (Window.width/1.5, Window.width/1.5))

        self.root = SM()
        return self.root

    def option_menu_function(self):
        self.popup.open()