Tkinter Entry get() Method
Entry has a get() method that can be used to get the contents of the current Entry string, and the Widget control has a common method, Quit, which ends the Python Shell window program when it is executed, but the window application continues to run.
Tkinter Entry get() Method Example#1
Add Login and Quit function buttons.
If the Login function button is clicked, the entered Account and Password will be listed in the Python Shell.
If you click the Quit button, the py execution in the Python Shell window will end, but this apidemos.com window will still be visible on the screen as executing.
from tkinter import *
def printInfo():
print("Account:%s\nPassword: %s" %(accountE.get(),pwdE.get()))
root = Tk()
root.title("apidemos.com")
msg = "Welcome to apidemos.com"
myPic = PhotoImage(file="apidemos.png")
logo = Label(root,image=myPic,text=msg,compound=BOTTOM)
accountL = Label(root,text="Account")
accountL.grid(row=1)
pwdL = Label(root,text="Password")
pwdL.grid(row=2)
logo.grid(row=0,column=0,columnspan=2,pady=10,padx=10)
accountE = Entry(root)
pwdE = Entry(root,show="*")
accountE.grid(row=1,column=1)
pwdE.grid(row=2,column=1,pady=10)
# The following Login and Quit buttons are created
loginbtn = Button(root,text="Login",command=printInfo)
loginbtn.grid(row=3,column=0)
quitbtn = Button(root,text="Quit",command=root.quit)
quitbtn.grid(row=3,column=1)
root.mainloop()
Output:
The following is the result of the execution in the Python Shell window after clicking the Login button and then pressing the Quit button.
From the above execution results, we can see that the Login button and Quit button are not aligned with the label and text box above. We can add the sticky parameter within the grid( ) method and set this parameter to W, which is a reliable left-aligned field.
Tkinter Entry get() Method Example#2
Use the sticky=W
parameter and the pady=5
parameter.
from tkinter import *
def printInfo():
print("Account:%s\nPassword: %s" %(accountE.get(),pwdE.get()))
root = Tk()
root.title("apidemos.com")
msg = "Welcome to apidemos.com"
myPic = PhotoImage(file="apidemos.png")
logo = Label(root,image=myPic,text=msg,compound=BOTTOM)
accountL = Label(root,text="Account")
accountL.grid(row=1)
pwdL = Label(root,text="Password")
pwdL.grid(row=2)
logo.grid(row=0,column=0,columnspan=2,pady=10,padx=10)
accountE = Entry(root)
pwdE = Entry(root,show="*")
accountE.grid(row=1,column=1)
pwdE.grid(row=2,column=1,pady=10)
# The following Login and Quit buttons are created
loginbtn = Button(root,text="Login",command=printInfo)
loginbtn.grid(row=3,column=0,sticky=W,pady=5)
quitbtn = Button(root,text="Quit",command=root.quit)
quitbtn.grid(row=3,column=1,sticky=W,pady=5)
root.mainloop()
Output: