I am getting None as name and age from the entry of Tkinter and I can't make it work. Please, what is wrong? The following code is identical with the one used in this tutorial:
from tkinter import *
from tkinter import Entry
main_window = Tk()
Label(main_window, text="Enter your name ").grid(row=0, column=0)
Label(main_window, text="What's your age ").grid(row=1, column=0)
my_name = Entry(main_window, width=30, borderwidth=5).grid(row=0, column=1)
my_age = Entry(main_window, width=30, borderwidth=5).grid(row=1, column=1)
def on_click():
print(f'My name is {my_name}, and my age is {my_age}.')
Button(main_window, text='Click Me', command=on_click).grid(row=2, column=1)
main_window.mainloop()
I read on youtube and here to try the get method, but I am just starting with programming, and I must be doing something wrong because nothing is working.
The return value from a call to .grid()
method is None. So both of the variables my_age
and my_name
value once the line has finished processing is None
and you no longer have a reference variable for the widgets. you need to split up the calls that create the objects and the call to grid
.
The same would be true for the labels also if you needed to keep a reference to them after they have been created. But since you don't you can leave those lines the way they are.
from tkinter import *
from tkinter import Entry
main_window = Tk()
Label(main_window, text="Enter your name ").grid(row=0, column=0)
Label(main_window, text="What's your age ").grid(row=1, column=0)
my_name = Entry(main_window, width=30, borderwidth=5)
my_name.grid(row=0, column=1)
my_age = Entry(main_window, width=30, borderwidth=5)
my_age.grid(row=1, column=1)
def on_click():
print(f'My name is {my_name}, and my age is {my_age}.')
Button(main_window, text='Click Me', command=on_click).grid(row=2, column=1)
main_window.mainloop()