Tkinter variable "Num1" referenced before assignment
Question:
I’m very new to Tkinter and don’t know exactly what I’m doing. I have these two entry widgets which are both numbers when entered. Whenever I press the "run" button to multiply the numbers I get a "variable referenced before assignment error" and I’m not sure why.
Here’s the code:
from tkinter import *
root = Tk()
def myClick1():
Num1 = int(Num1.get())
Num2 = int(Num2.get())
print(Num1 * Num2)
Num1 = Entry(root, bg = "black", fg = "red", border = 10, justify = RIGHT)
Num2 = Entry(root, bg = "black", fg = "blue", border = 10, justify = RIGHT)
RAD2=Radiobutton(root, text = "Run", command = myClick1, fg = "red", bg = "black", border = 12)
RAD2.pack()
Num1.pack()
Num2.pack()
root.mainloop()
Any help would be appreciated.
Answers:
In python, global variables such as Num1
and Num2
are available globally, as the name implies. However, if you try to assign a new value to a variable in a function, that variable automatically becomes local.
Thus, when you do Num1 = int(Num1.get())
, Num1
is considered to be a local variable. And since you have not assigned a local variable named Num1
prior to this statement, Num1.get()
fails.
If you rename the local variable Num1
and Num2
to something else, this will work.
def myClick1():
num1 = int(Num1.get())
num2 = int(Num2.get())
print(num1 * num2)
I’m very new to Tkinter and don’t know exactly what I’m doing. I have these two entry widgets which are both numbers when entered. Whenever I press the "run" button to multiply the numbers I get a "variable referenced before assignment error" and I’m not sure why.
Here’s the code:
from tkinter import *
root = Tk()
def myClick1():
Num1 = int(Num1.get())
Num2 = int(Num2.get())
print(Num1 * Num2)
Num1 = Entry(root, bg = "black", fg = "red", border = 10, justify = RIGHT)
Num2 = Entry(root, bg = "black", fg = "blue", border = 10, justify = RIGHT)
RAD2=Radiobutton(root, text = "Run", command = myClick1, fg = "red", bg = "black", border = 12)
RAD2.pack()
Num1.pack()
Num2.pack()
root.mainloop()
Any help would be appreciated.
In python, global variables such as Num1
and Num2
are available globally, as the name implies. However, if you try to assign a new value to a variable in a function, that variable automatically becomes local.
Thus, when you do Num1 = int(Num1.get())
, Num1
is considered to be a local variable. And since you have not assigned a local variable named Num1
prior to this statement, Num1.get()
fails.
If you rename the local variable Num1
and Num2
to something else, this will work.
def myClick1():
num1 = int(Num1.get())
num2 = int(Num2.get())
print(num1 * num2)