首页 > 解决方案 > kivy FileChooserListView on_selection 事件未按预期工作

问题描述

我试图通过绑定到更新文本标签的方法来观察selectionFileChooserListView 对象的属性(ObservableList) 。on_selection

根据我对 kivy 文档的解释,我认为下面的代码可以工作,但是没有多少点击或双击文件名会导致标签被更新或打印语句被执行。我是否误解了有关on_<property>变更事件的文档?

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.filechooser import FileChooserListView


class FCApp(App):
    def build(self):
        my_layout = AppLayout()
        return my_layout


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

        self.orientation = 'vertical'
        self.lbl = Label(size_hint_y=0.1, text='Select a file...')
        self.fc = FileChooserListView(size_hint_y=0.9)

        # Bind changes to the file chooser's selection property to a function
        self.fc.bind(on_selection=self.update_label)

        self.add_widget(self.lbl)
        self.add_widget(self.fc)

    def update_label(self, obj):
        print('update_label_called')
        self.lbl.text = str(obj.selection)


if __name__ == '__main__':
    FCApp().run()

标签: pythonkivy

解决方案


如果您on_<property>扩展FileChooserListView. 在这种情况下,您可以定义文档on_selection()中描述的方法。

或者您可以Property将绑定中的名称用作:

self.fc.bind(selection=self.update_label)

如此处所述。

假设您只是更改绑定代码,则需要修改您的update_label()方法:

def update_label(self, fc_instance, selection):
    print('update_label_called')
    self.lbl.text = str(selection)

推荐阅读