赋值前引用的局部变量 (TKINTER)

Local variable referenced before assignment (TKINTER)

我收到 UnboundLocalError

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:\Users\Ya Bish\Projects\Obracun Sati\main.py", line 249, in item_selected
app = EmpWindow(top,record)
UnboundLocalError: local variable 'record' referenced before assignment

当询问文件名和

def __init__(self,master):
    self.master = master
    self.openButton = Button(self.frame, text="Open", 
    command=self.openFile)
    ...
    self.tree = Treeview(self.master, columns=self.columns, show="headings")
    ...
    self.tree.bind('<<TreeviewSelect>>', self.item_selected)
def openFile(self):
    ...
    self.tree.delete(*self.tree.get_children())
    filename = filedialog.askopenfilename()
    calc(filename)
    for e in emps:
        self.tree.insert('', END, values=e.treeValues)
    

虽然此 Toplevel() window 处于活动状态或之前已经处于活动状态。

def item_selected(self, event):
    for selected_item in self.tree.selection():
        item = self.tree.item(selected_item)
        record = item['values'][0]
    top = Toplevel()
    app = EmpWindow(top,record)
    top.mainloop()

EmpWindow 只是一个笔记本 class,定义了两个选项卡和几个标签,所以我认为代码不是必需的。 这可能是 eventBind 的错误,但我根本不理解那部分,所以我什至不知道如何处理它.

这可能是因为 item_selected 中的 for-loop 甚至没有进行一次迭代,在这种情况下 record 将永远不会被定义。其简化版本如下

def f():
    for x in range(0):
        print(x)

    print(x)

f()

这给出了与您的代码完全相同的错误。每当您在函数内部分配变量之前引用变量时,就会发生这种错误。