Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Local variable referenced before assignment (TKINTER)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading