I am trying to implement a login system for a program I am making. The issue is in trying to retrieve the input and store it in a variable when the user clicks submit.
I have already read several articles on this, but none seem to work. The following has program has had several section removed, but encounters the same issue.
#Imports
import tkinter
#Initilization
master = tkinter.Tk()
#Defineing Variables
#Submit
def Submit():
print("Creating Account...")
master.destroy()
#Cancel
def Cancel():
print("Login failed!")
master.destroy()
#Build GUI
def BuildGUI():
#Lables
tkinter.Label(master, text="All avalibe feilds required.").grid(row=0)
tkinter.Label(master, text="First Name").grid(row=1)
#Input Fileds
User_NameFirst = tkinter.StringVar()
e1 = tkinter.Entry(master, textvariable=User_NameFirst)
e1.grid(row=1, column=1)
#Buttons
tkinter.Button(master, text='Cancel', command=Cancel).grid(row=11, column=0, sticky='W', pady=4)
tkinter.Button(master, text='Enter', command=Submit).grid(row=11, column=1, sticky='W', pady=4)
tkinter.Button(master, text='Test', command=print(e1.get())).grid(row=12, sticky='W', pady=6, padx=6)
#Debug
BuildGUI()
#Mainloop
tkinter.mainloop()
I expected, that when I click "test", that the program would print the value that I imputed into e1 to be printed. However, nothing happens. I did notice that, when I start the program, the terminal seems output a few blank lines.
The comment by Henry Yik is correct- as demonstrated by https://stackoverflow.com/a/5771787/11006183, The print()
statement was executed before I clicked the button.
To fix it, I needed to use the lambda
function:
tkinter.Button(master, text='Test', command=lambda: print(e1.get()) ).grid(row=12, sticky='W', pady=6, padx=6)