【问题标题】:Python 3 "Using variable before assignment" but only in 1 of 2 functionsPython 3“在赋值前使用变量”但仅在 2 个函数中的 1 个中
【发布时间】:2019-12-17 08:49:19
【问题描述】:

我有一个非常奇怪的错误。首先,我的代码(当然什么都没有):

import os
import tkinter

frame = tkinter.Frame(main)


listbox = tkinter.Listbox(frame, height=23)
for name in files:
    listbox.insert('end', name)


def play():
    list_element = listbox.get(0,'end')
    list_selection = listbox.curselection()
    selected_element = list()
    for list_index in list_selection:
        selected_element.append(list_element[int(list_index)])

def openfolder():
    list_element = listbox.get(0,'end')         #here I get the error
    list_selection = listbox.curselection()
    selected_element = list()
    for list_index in list_selection:
        selected_element.append(list_element[int(list_index)])

我有一个列表框 (tkinter),它显示文件/文件夹。我需要

list_element = listbox.get(0,'end')         
    list_selection = listbox.curselection()
    selected_element = list()
    for list_index in list_selection:
        selected_element.append(list_element[int(list_index)])

block 获取选定的文件/文件夹作为 selected_element[0]。在第一个函数 play() 中,一切正常。但在第二个函数 openfolder() 中,我收到错误“在赋值前使用变量列表框”,但它与游戏中的代码相同(我复制了它)。

当我使用“全局列表框”时,selected_element 为空(当我打印它时,它显示:“[]”,当我尝试打印 selected_element[0] 时,我收到错误“列表索引超出范围” ) [是的,我选择了一个文件夹]。

有没有办法解决这个问题?我不知道有什么区别,在 play() 中效果很好。

顺便说一句,我用按钮(tkinter)调用这个函数。

非常感谢

我的整个代码:https://pastebin.com/Tf01Ei2d

【问题讨论】:

    标签: python python-3.x file tkinter listbox


    【解决方案1】:

    很难说出为什么会发生此错误,因为您没有发布实际调用这些方法的方式。

    但是,在方法@​​987654321@ 和openfolder() 中,变量listbox 是未知的,因为您没有在在方法范围内 的任何地方声明它。因此,最简单的方法可能是将您的 listbox 作为参数移交给这两种方法:

    def play(listbox):
       <algorithm>
    
    def openfolder(listbox):
       <algorithm>
    

    【讨论】:

      【解决方案2】:

      找到了!我只需要删除列表框 (listbox.delete(0, tkinter.END)),而不是在其上创建一个新列表框 (listbox = tkinter.Listbox(frame, height=23))。

      【讨论】:

        猜你喜欢
        • 2021-03-13
        • 1970-01-01
        • 1970-01-01
        • 2018-03-12
        • 1970-01-01
        • 2022-01-13
        • 2016-12-07
        • 2013-07-04
        • 2021-07-30
        相关资源
        最近更新 更多