Python 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:

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. 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:

e1.bind("", 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:

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.

Python Entry Widget Example

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

from tkinter import * 
class MyEntry: 
   def __init__(self, root): 
      self.f = Frame(root, height=350, width=500) 
      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), y=100), y=100), y=150), 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)