Python tkinter Entry widget

Entry widget is useful to create a rectangular box that can be used to enter or display one line of text.For example, we can display names, passwords or credit card numbers using Entry widgets.An Entry widget can be created as an object of Entry class as:

Syntax

CopiedCopy Code
e1 = Entry(f, width=25, fg='blue', bg='yellow', font=('Arial', 14), show='*')

Here, 'e1' is the Entry class object. 'f' indicates the frame which is the parent component for the Entry widget.'width' represents the size of the widget in number of characters.'fg' indicates the fore ground color in which the text in the widget is displayed.'bg' represents the back ground color in the widget.'font' represents a tuple that contains font family name, size and style.'show' represents a character that replaces the originally typed characters in the Entry widget.For example, show='*' is useful when the user wants to hide his password by displaying stars in the place of characters.

tkinter Entry widget with bind() method

After typing text in the Entry widget, the user presses the Enter button. Such an event should be linked with the Entry widget using bind() method as:

CopiedCopy Code
e1.bind("<Return>", self.display)

When the user presses Enter (or Return) button, the event is passed to display() method.Hence, we are supposed to catch the event in the display method, using the following statement:

CopiedCopy Code
def display(self, event):

As seen in the preceding code, we are catching the event through an argument 'event' in the display() method.This argument is never used inside the method.The method consists of the code that is to be executed when the user pressed Enter button.

tkinter Entry widget with bind() example

A Python program to create Entry widgets for entering user name and password and display the entered text

CopiedCopy Code

from tkinter import * 
class MyEntry: 
   def __init__(self, root): 
      self.f = Frame(root, height=350, width=500) 
      self.f.propagate(0) 
      self.f.pack() 
      self.l1 = Label(text='Enter User name:') 
      self.l2 = Label(text='Enter Password:') 
      self.e1 = Entry(self.f,width=25,fg='blue',bg='yellow',font=('Arial', 14)) 
      self.e2 = Entry(self.f,width=25, fg='blue',bg='yellow',show='*')
      self.e2.bind("Return",self.display) 
      self.l1.place(x=50, y=100) 
      self.e1.place(x=200, y=100) 
      self.l2.place(x=50, y=150) 
      self.e2.place(x=200, y=150) 
   def display(self, event): 
      str1 = self.e1.get() 
      str2 = self.e2.get() 
      lbl1 = Label(text='Your name is: '+str1).place(x=50, y=200) 
      lbl2 = Label(text='Your password is: '+str2).place(x=50, y=220)
      root = Tk() 
      mb = MyEntry(root) 
      root.mainloop()