代码之家  ›  专栏  ›  技术社区  ›  tommccann

如何加载文件选择器对话框

  •  0
  • tommccann  · 技术社区  · 6 年前

    我是一个Kivy新手,尽管我读过几本书,相当多的Kivy文档,看过很多例子,但我仍然很难找到如何构建我的程序的方法。我正在尝试让一个文件选择器对话框工作。

    我想从一个简单的BoxLayout界面开始,只需一个按钮。按此按钮时,我想显示文件选择器对话框。我从其中一本书中提取了很多代码。我的问题是如何调用LoadDialog小部件/类。我知道我的按钮不应该引用根。show_load_list(),但我不确定该如何引用它。如果你能给我一个正确的方向,我将不胜感激。

    # File name: main.py
    from kivy.app import App
    
    from kivy.uix.floatlayout import FloatLayout
    from kivy.properties import ObjectProperty
    from kivy.lang import Builder
    
    
    class LoadDialog(FloatLayout):
        load = ObjectProperty(None)
        cancel = ObjectProperty(None)
    
        def show_load_list(self):
            content = LoadDialog(load=self.load_list, cancel=self.dismiss_popup)
            self._popup = Popup(title="Load a file list", content=content, size_hint=(1, 1))
            self._popup.open()
    
        def load_list(self, path, filename):
            pass
    
        def dismiss_popup(self):
            self._popup.dismiss()
    
    class LoadDialogApp(App):
        pass
    
    if __name__ == '__main__':
        LoadDialogApp().run()
    

    我的kv文件定义为

    # File name: loaddialog.kv
    
    BoxLayout:
        Button:
            text: "Click me"
            on_release: root.show_load_list()
    
    <LoadDialog>:
        BoxLayout:
            size: root.size
            pos: root.pos
            orientation: "vertical"
            FileChooserListView:
                id: filechooser
                path: './'
            BoxLayout:
                size_hint_y: None
                height: 30
                Button:
                    text: "Cancel"
                    on_release: root.cancel()
                Button:
                    text: "Load"
                    on_release: root.load(filechooser.path, filechooser.selection)
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   ikolim    5 年前

    Python代码

    1. from kivy.uix.popup import Popup
    2. 重命名类 LoadDialog Root

    片段

    from kivy.uix.popup import Popup
    
    
    class LoadDialog(FloatLayout):
        load = ObjectProperty(None)
        cancel = ObjectProperty(None)
    
    
    class Root(FloatLayout):
        load = ObjectProperty(None)
        cancel = ObjectProperty(None)
    
        def show_load_list(self):
    

    1. 添加根规则, Root: 之前 BoxLayout:

    片段

    Root:
        BoxLayout:
            Button:
                text: "Click me"
                on_release: root.show_load_list()
    
    <LoadDialog>:
        BoxLayout:
    

    Img01