在kivy弹出窗口中选择文件时出现索引错误

问题描述

def popping(self,button_instance):
        self.small_page = Popup(title='Choose jpg or png file',size_hint=(.8,.8))
        self.scroll = ScrollView()
        self.small_page.add_widget(self.scroll)
        file_choose = FileChooserListView()
        self.scroll.add_widget(file_choose)
        self.upload_pic = Button(text='Upload',size_hint=(1,.2),on_press= self.uploading(file_choose.selection))
        self.small_page.add_widget(self.upload_pic)
          
        
        
        self.small_page.open()
        
def uploading(self,filename):
        profile_pic.source = filename[0]

我有一个kivy弹出窗口,转到文件选择器,每次我尝试访问文件时都会出现错误,如果可能的话,可以用python语言而不是kivy编写答案。

IndexError: list index out of range
            

解决方法

问题出在那一行:

self.upload_pic = Button(text='Upload',size_hint=(1,.2),on_press= self.uploading(file_choose.selection))

在定义self.uploading(file_choose.selection)时,该行将执行Button,远远早于您在FileChooser中选择任何内容之前的那一行。您可以使用partial定义要调用的函数,如下所示:

self.upload_pic = Button(text='Upload',on_press=partial(self.uploading,file_choose))

partial定义了一个函数(及其args),但未调用它。然后,您的self.uploading()方法可能类似于:

def uploading(self,file_chooser,button):
    print(file_chooser.selection[0])