【问题标题】:Opening a custom DropDown with the DropDown open() method does not work使用 DropDown open() 方法打开自定义 DropDown 不起作用
【发布时间】:2017-12-02 03:07:27
【问题描述】:

我确实在 kv 文件中定义了一个基本的自定义 DropDown。应用程序的 GUI 非常简单,顶部有一个按钮栏,屏幕的其余部分是一个 TextInput。代码如下:

dropdowntrialgui.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.dropdown import DropDown

class CustomDropDown(DropDown):
    pass

class DropDownTrialGUI(BoxLayout):
    dropD = CustomDropDown()

    def openMenu(self, widget):
        self.dropD.open(widget)


class DropDownTrialGUIApp(App):
    def build(self):
        return DropDownTrialGUI()


if __name__== '__main__':
    dbApp = DropDownTrialGUIApp()

    dbApp.run()

还有kv文件:

dropdowntrialgui.kv

DropDownTrialGUI:

    <CustomDropDown>
        Button:
            text: 'My first Item'
            size_hint_y: None
            height: '28dp'
            on_release: root.select('item1')
        Button:
            text: 'My second Item'
            size_hint_y: None
            height: '28dp'
            on_release: root.select('item2')

    <DropDownTrialGUI>:
        orientation: "vertical"
        padding: 10
        spacing: 10

        BoxLayout:
            size_hint_y: None
            height: "28dp"
            Button:
                id: toggleHistoryBtn
                text: "History"
                size_hint_x: 15
            Button:
                id: deleteBtn
                text: "Delete"
                size_hint_x: 15
            Button:
                id: replaceBtn
                text: "Replace"
                size_hint_x: 15
            Button:
                id: replayAllBtn
                text: "Replay All"
                size_hint_x: 15
            Button:
                id: menuBtn
                text: "..."
                size_hint_x: 15
                on_press: root.openMenu(self)

        TextInput:
            id: readOnlyLog
            size_hint_y: 1
            readonly: True

按 menuBtn 无效。我该如何解决这个问题?

【问题讨论】:

    标签: android python-3.x kivy kivy-language


    【解决方案1】:

    您没有正确初始化类,作为一般规则,您不应该将任何东西定义为类属性(kivy 属性除外),而是通过在 __init__ 方法中实例化小部件来将它们定义为实例属性:

    class DropDownTrialGUI(BoxLayout):
        def __init__(self, **kwargs):
            super(DropDownTrialGUI, self).__init__(**kwargs)
            self.dropD = CustomDropDown()
    
        def openMenu(self, widget):
            self.dropD.open(widget)
    

    【讨论】:

      猜你喜欢
      • 2015-09-23
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-15
      • 2015-09-15
      • 2023-02-22
      相关资源
      最近更新 更多