So I'm writing a simple Python GUI program to generate random numbers and keep getting this error: 'NoneType' object has no attribute 'get'
def ButClick():
try:
MinNum = int (txt1.get())
MaxNum = int (txt2.get())
Num = int (txt3.get())
except ValueError:
messagebox.showerror("ValueError", "Error! Invalid numbers")
else:
Nums = ''
if MinNum <= MaxNum:
i = 0
while i < Num:
numOne = randint(MinNum,MaxNum)
Nums = Nums + ":" + str(numOne)
i += 1
scr.insert(INSERT, str(Nums) + "\n")
else:
messagebox.showerror("NumError!!", "Error! Invalid Numbers!")
pass
root = Tk()
root.title("Random is so random :)")
lb1 = Label(root, text = "Min number").grid(
row = 0,
column = 0,
pady = 10,
padx = 10)
txt1 = Entry(root, width = 30).grid(
row = 0,
column = 1,
pady = 10,
padx = 10)
lb2 = Label(root, text = "Max number").grid(
row = 1,
column = 0,
pady = 10,
padx = 10)
txt2 = Entry(root, width = 30).grid(
row = 1,
column = 1,
pady = 10,
padx = 10)
lb3 = Label(root, text = "number").grid(
row = 2,
column = 0,
pady = 10,
padx = 10)
txt3 = Entry(root, width = 30).grid(
row = 2,
column = 1,
pady = 10,
padx = 10)
but = Button(root, width = 15, height = 2, text = "Generate", command = ButClick).grid(
row = 3,
column = 0,
columnspan = 2,
pady = 10,
padx = 10)
scr = scrolledtext.ScrolledText(root, height = 10).grid(
row = 4,
column = 0,
columnspan = 2,
pady = 10,
padx = 10)
How can I fix it? Maybe its because I need to use the older version of Python? I tried to install python 3.7.3 version via terminal but it was in vain. I watched other questions on this topic but couldn't find any specifically on attribute .get
grid()
does not return anything, which is why all your variables like txt2
and lb1
end up as None
, hence the error. I believe what you want to do is:
txt1 = Entry(root, width = 30)
txt1.grid(
row = 0,
column = 1,
pady = 10,
padx = 10)
Of course same goes for all other UI elements. Notice how the code first creates an element and stores it in a variable, and only then, separately, positions the element in the grid.