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.
JavaScript
x
23
23
1
import tkinter as tk
2
3
root = tk.Tk()
4
5
root.title("TKinter Test")
6
7
canvas = tk.Canvas(root, width=500, height=500)
8
9
Increment = 0
10
11
12
def reply():
13
#FIG 1 FIG 2
14
Increment = Increment + 1
15
print(Increment)
16
print("Reply")
17
18
19
Button = tk.Button(root, width=30, height=10, command=reply, text="Status")
20
Button.pack(padx=10, pady=10)
21
22
root.mainloop()
23
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:
JavaScript
1
24
24
1
import tkinter as tk
2
3
root = tk.Tk()
4
5
root.title("TKinter Test")
6
7
canvas = tk.Canvas(root, width=500, height=500)
8
9
Increment = 0
10
11
12
def reply():
13
#FIG 1 FIG 2
14
global Increment
15
Increment += 1
16
print(Increment)
17
print("Reply")
18
19
20
Button = tk.Button(root, width=30, height=10, command=reply, text="Status")
21
Button.pack(padx=10, pady=10)
22
23
root.mainloop()
24