Kivy manual中的示例是使用具有猕猴桃语言的FileChooser。我只想在python代码中使用FileChooser。当我用鼠标标记目录时,请按“选择目录”按钮,并且实际值在变量FileChooser.path中。不使用此按钮的选择不会导致。
在示例中使用的kv文件中,使用了事件on_selection,我将此事件与函数绑定在一起,但没有效果。
我的问题:
如何仅使用鼠标就能获得路径的价值?
哪个类使用事件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
,在FileChooserListView
中有属性selection。您在具有这些属性的类中can use functions on_<propname>
,但是在使用bind时,应仅使用bind(<propname>=
。
第二件事是,默认情况下,如您在doc 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/