【问题标题】:Index error when choosing file in a kivy popup window在 kivy 弹出窗口中选择文件时出现索引错误
【发布时间】:2020-08-14 11:05:03
【问题描述】:
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
            

【问题讨论】:

    标签: python list kivy filechooser index-error


    【解决方案1】:

    问题出在这行:

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

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

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

    partial 定义了一个函数(及其参数),但没有调用它。那么你的self.uploading() 方法可以是这样的:

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

    【讨论】:

    • 非常感谢它的工作,对于其他想使用部分的人,您需要通过以下方式导入部分:from functools import partial
    猜你喜欢
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多