首页 > 解决方案 > 为什么我的 kivy 下拉菜单没有显示(Python)?

问题描述

我目前正在尝试用 kivy 制作词汇训练器,以便可以在手机上使用它。但我不知何故被困在下拉菜单中。我使用了 kivy wiki 中的下拉菜单示例并进行了一些更改,使其适合我现有的代码。我现在的问题是下拉菜单没有显示,python 也没有给我一个错误。我已经尝试了一些其他可能的解决方案,这些解决方案也对我不起作用,以及通过 try 进行调试 - 除了和 pycharm 调试器。

class FloatLayout(FloatLayout):
    def __init__(self, **kwargs):
        super(FloatLayout, self).__init__(**kwargs)
        self.dropdown = DropDown()
        self.languages = ["language1", "language2", "language3"]
        for i in self.languages:
            btn = Button(text="%r" % i, size_hint_y=None, height=30)
            btn.bind(on_release=lambda btn: self.dropdown.select(btn.text))
            self.dropdown.add_widget(btn)

        self.dropdownButton = Button(text="Language selection", size_hint=(None, None), pos_hint={"x": 0.5, "top": 0.5})
        self.dropdownButton.bind(on_release=self.dropdown.open)
        self.dropdown.bind(on_select=lambda instance, x: setattr(self.dropdownButton, "text", x))
class KivyGUI(App):
    def build(self):
        return FloatLayout()
if __name__ == "__main__":
    runKivy()

所有的帮助和赞赏。谢谢!

标签: pythondrop-down-menukivy

解决方案


问题 1

需要添加self.dropdownButton到根小部件,FloatLayout.

self.add_widget(self.dropdownButton)

问题 2

替换runKivy()KivyGUI().run()

片段

        self.dropdown.bind(on_select=lambda instance, x: setattr(self.dropdownButton, "text", x))
        self.add_widget(self.dropdownButton)

class KivyGUI(App):
    def build(self):
        return FloatLayout()


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

输出

结果


推荐阅读