Home > Net >  Local variable referenced before assignment (TKINTER)
Local variable referenced before assignment (TKINTER)

Time:04-09

I'm getting an 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

when asking for filename and

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)
    

while this Toplevel() window is either active or have been previously active.

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 is just a notebook class with two tabs defined and couple of labels so I don't think that code is necessary. This may be an error with event and Bind but I don't understand that part at all so I don't even know how to approach it.

CodePudding user response:

This might be happening because your for-loop in item_selected is not even getting a single iteration in which case record will never be defined. A simplified version of this is the following

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

    print(x)

f()

This gives the exact same error as your code. This kind of error occurs whenever you reference a variable before you assign it inside functions.

  • Related