When attempting to put some maths that change a variable within a definition, I receive an error specifying “Unresolved Reference”. The following is the code I am using, the relevant code on lines 9 – 15.
import tkinter as tk root = tk.Tk() root.title("TKinter Test") canvas = tk.Canvas(root, width=500, height=500) Increment = 0 def reply(): #FIG 1 FIG 2 Increment = Increment + 1 print(Increment) print("Reply") Button = tk.Button(root, width=30, height=10, command=reply, text="Status") Button.pack(padx=10, pady=10) root.mainloop()
The first “Increment” which is under “FIG 1”: incurs the error “Shadows name ‘Increment’ from outer scope”. The second one (under “FIG 2”) causes the “Unresolved Reference” error I already talked about.
Advertisement
Answer
Your Increment variable is a global variable.
So inside your reply function this variable is not known.
You need to add global inside reply function:
import tkinter as tk root = tk.Tk() root.title("TKinter Test") canvas = tk.Canvas(root, width=500, height=500) Increment = 0 def reply(): #FIG 1 FIG 2 global Increment Increment += 1 print(Increment) print("Reply") Button = tk.Button(root, width=30, height=10, command=reply, text="Status") Button.pack(padx=10, pady=10) root.mainloop()