python - Kivy:如何在没有kv语言的情况下通过FileChooser选择目录?

标签 python kivy kivy-language

Kivy manual是使用 kivy 语言使用 FileChooser 的示例。我只想在 python 代码中使用 FileChooser 。当我用鼠标标记目录时,按下按钮选择目录,实际值位于变量FileChooser.path中。不使用此按钮的选择不会产生结果。 在示例中的 kv 文件中使用了事件 on_selection,我将此事件与我的函数绑定(bind),但没有效果。

我的问题:

  1. 如何仅使用鼠标获取路径值?
  2. 哪个类使用事件on_selection

谢谢!

class Explorer(BoxLayout):   
    def __init__(self, **kwargs):
        super(Explorer,self).__init__(**kwargs)

        self.orientation = 'vertical'
        self.fichoo = FileChooserListView(size_hint_y = 0.8)
        self.add_widget(self.fichoo)

        control   = GridLayout(cols = 5, row_force_default=True, row_default_height=35, size_hint_y = 0.14)
        lbl_dir   = Label(text = 'Folder',size_hint_x = None, width = 80)
        self.tein_dir  = TextInput(size_hint_x = None, width = 350)
        bt_dir = Button(text = 'Select Dir',size_hint_x = None, width = 80)
        bt_dir.bind(on_release =self.on_but_select)

        self.fichoo.bind(on_selection = self.on_mouse_select)

        control.add_widget(lbl_dir)
        control.add_widget(self.tein_dir)
        control.add_widget(bt_dir)

        self.add_widget(control)

        return

    def on_but_select(self,obj):
        self.tein_dir.text = str(self.fichoo.path)
        return

    def on_mouse_select(self,obj):
        self.tein_dir.text = str(self.fichoo.path)
        return

    def on_touch_up(self, touch):
        self.tein_dir.text = str(self.fichoo.path)
    return super().on_touch_up(touch)
        return super().on_touch_up(touch)

最佳答案

需要进行一些更改。

没有这样的事件on_selection ,有属性(property)selectionFileChooserListView 。您can use functions on_<propname>在具有这些属性的类内部,但是当您使用绑定(bind)时,您应该仅使用 bind(<propname>= .

第二件事是默认情况下,正如您在文档 selection 中看到的那样包含选定文件的列表,而不是目录。要使目录实际上可以选择,您应该更改 dirselect属性至True .

最后是on_mouse_select签名:属性以其值触发,您应该计算它。

更改摘要为:

self.fichoo.dirselect = True
self.fichoo.bind(selection = self.on_mouse_select)

# ... and

def on_mouse_select(self, obj, val):

之后,您将执行与按钮相同的操作。

<小时/>

如果您想填充输入的不是您实际所在的路径,而是所选路径,您可以执行以下操作:

def on_touch_up(self, touch):
    if self.fichoo.selection:
        self.tein_dir.text = str(self.fichoo.selection[0])
    return super().on_touch_up(touch)

关于python - Kivy:如何在没有kv语言的情况下通过FileChooser选择目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48132151/

相关文章:

python - 在 Kivy 中使用变量和函数时未定义名称

android - Android 上的 Kivy : Keep Kivy clock running even when app is minimized

Python Kivy 并将本地照片添加到 Carousel

python-3.x - 如何使用kv语言引用kivy中创建的不同屏幕的小部件?

python - so_reuseport下如何连接到特定的grpc服务器进程

Python PULP 数组乘法约束

python - Kivy 的外观和感觉

python - 基维 : how to add vertical scrollbar in boxlayout

Python - Mailchimp 批量 PUT 请求

python - 将业务层错误与 API 错误分开