How to Use Tkinter Entry Widget in Python?

In this tutorial, I will explain how to use Tkinter Entry widget in Python to accept user input in your GUI applications. The Entry widget allows users to enter and display a single line of text. I’ll explain several examples using common American names to demonstrate how to create, customize, and retrieve data from Entry widgets.

Create an Entry Widget in Python Tkinter

To create a basic Entry widget, you first need to import the Tkinter module and create a root window. Then, use the Entry() constructor to create the widget. Here’s an example:

import tkinter as tk

root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
root.mainloop()

I have executed the above code and added the screenshot below.

Use Tkinter Entry Widget in Python

This code creates a simple window with an Entry widget where the user can type in their input, such as their name. For instance, if the user’s name is “John Smith”, they can enter it into the widget.

Read Python Tkinter to Display Data in Textboxes

Configure Entry Widget Properties

You can customize various properties of the Entry widget using the config() method. Some common properties include:

  • width: Set the width of the widget in characters
  • font: Specify the font style and size
  • bg and fg: Set the background and foreground colors
  • show: Mask the entered characters (useful for password fields)

Here’s an example that creates an Entry widget with a width of 30 characters, Arial font, and a light gray background:

entry = tk.Entry(root, width=30, font=("Arial", 12), bg="yellow")

I have executed the above code and added the screenshot below.

Tkinter Entry Widget in Python

Now, when a user like “Emily Johnson” enters her name, it will appear in the specified font and color.

Read How to Set Background to be an Image in Python Tkinter

Retrieve User Input

To retrieve the text entered in an Entry widget, you can use the get() method. Here’s an example that demonstrates how to fetch and print the user input:

def print_input():
    user_input = entry.get()
    print("User entered:", user_input)

button = tk.Button(root, text="Submit", command=print_input)
button.pack()

I have executed the above code and added the screenshot below.

How to Use Tkinter Entry Widget in Python

In this code, clicking the “Submit” button triggers the print_input() function, which retrieves the text from the Entry widget entry.get() and prints it to the console. So, if the user enters “Hello”, that word will be printed when the button is clicked.

Read How to Create Countdown Timer using Python Tkinter

Validate User Input

To restrict the characters that can be entered into an Entry widget, you can use the validatecommand option along with a validation function. Here’s an example that allows only uppercase letters and spaces:

def validate_input(text):
    allowed_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
    for char in text:
        if char not in allowed_chars:
            return False
    return True

entry = tk.Entry(root, validate="key", validatecommand=(root.register(validate_input), "%S"))

In this case, if a user like “Sarah Davis” tries to enter her name, only the uppercase letters “SARAH” and the space will be accepted. Lowercase letters and other characters will be rejected.

I have executed the above code and added the screenshot below.

Use Tkinter Entry Widget in Python validate user

Read Upload a File in Python Tkinter

Use Entry Widgets in Forms

Entry widgets are often used in forms to collect various types of user input. Here’s an example of a simple form that asks for the user’s name, email, and phone number:

name_label = tk.Label(root, text="Name:")
name_label.pack()
name_entry = tk.Entry(root)
name_entry.pack()

email_label = tk.Label(root, text="Email:")
email_label.pack()
email_entry = tk.Entry(root)
email_entry.pack()

phone_label = tk.Label(root, text="Phone:")
phone_label.pack()
phone_entry = tk.Entry(root)
phone_entry.pack()

def submit_form():
    name = name_entry.get()
    email = email_entry.get()
    phone = phone_entry.get()
    print("Name:", name)
    print("Email:", email) 
    print("Phone:", phone)

submit_button = tk.Button(root, text="Submit", command=submit_form)
submit_button.pack()

I have executed the above code and added the screenshot below.

Use Tkinter Entry Widget in Python entry widget

When the user fills out the form with their information, such as:

  • Name: Jennifer Wilson
  • Email: jennifer.wilson@example.com
  • Phone: (555) 123-4567

and clicks the “Submit” button, the submit_form() function retrieves the values from each Entry widget and prints them to the console.

Read Python Tkinter drag and drop

Display Default Text

You can display default or placeholder text in an Entry widget using the insert() method. This text will be displayed when the widget is empty and disappear once the user starts typing. Here’s an example:

entry = tk.Entry(root)
entry.insert(0, "Enter your name")

I have executed the above code and added the screenshot below.

Use Tkinter Entry Widget in Python default text

Now, when the user focuses on the Entry widget, they will see “Enter your name” as the default text. If the user is named “Robert Anderson”, he can simply start typing his name, and the default text will be replaced.

Read How to Create Date Time Picker using Python Tkinter

Style Entry Widgets

To make your Entry widgets visually appealing, you can apply styles using the ttk module. Here’s an example that creates a styled Entry widget:

from tkinter import ttk

style = ttk.Style()
style.configure("MyEntry.TEntry", padding=10, font=("Helvetica", 12))

entry = ttk.Entry(root, style="MyEntry.TEntry")

I have executed the above code and added the screenshot below.

Use Tkinter Entry Widget in Python style entry

This code defines a custom style named “MyEntry.TEntry” with specific padding and font properties. The Entry widget is then created using the ttk.Entry() constructor and assigned the custom style.

Read How to go to next page in Python Tkinter Program

Handle Entry Widget Events

You can bind events to Entry widgets to perform actions based on user interactions. Some common events include:

  • <FocusIn>: Triggered when the widget gains focus
  • <FocusOut>: Triggered when the widget loses focus
  • <Return>: Triggered when the Enter key is pressed

Here’s an example that displays a message when the Entry widget gains focus:

def on_focus_in(event):
    print("Entry widget focused")

entry.bind("<FocusIn>", on_focus_in)

I have executed the above code and added the screenshot below.

Use Tkinter Entry Widget in Python handle entry

Now, when a user like “Jessica Thompson” clicks on the Entry widget to enter her name, the message “Entry widget focused” will be printed to the console.

Read How to read a text file using Python Tkinter

Display Data in a Table Using Entry Widgets

Entry widgets can also be used to display data in a tabular format. Here’s an example that demonstrates how to create a simple table using Entry widgets:

data = [
    ["John", "Doe", "john.doe@example.com"],
    ["Jane", "Smith", "jane.smith@example.com"],
    ["Michael", "Johnson", "michael.johnson@example.com"]
]

for i in range(len(data)):
    for j in range(len(data[i])):
        entry = tk.Entry(root, width=20)
        entry.grid(row=i, column=j)
        entry.insert(tk.END, data[i][j])

I have executed the above code and added the screenshot below.

Use Tkinter Entry Widget in Python table

This code creates a grid of Entry widgets and populates them with data from the data list. Each row represents a person’s information (first name, last name, and email), and each column represents a specific field.

Read How to Take User Input and Store in Variable using Python Tkinter

Tkinter Entry Set Text

To set the text of a Tkinter Entry widget programmatically, you can use the insert() method. Here’s an example that demonstrates how to set the text of an Entry widget using a button:

import tkinter as tk

def set_entry_text():
    name = "John Doe"
    entry.delete(0, tk.END)  # Clear any existing text
    entry.insert(0, name)   # Set the new text

root = tk.Tk()
root.title("Entry Set Text Example")

entry = tk.Entry(root, width=30)
entry.pack()

button = tk.Button(root, text="Set Name", command=set_entry_text)
button.pack()

root.mainloop()

I have executed the above code and added the screenshot below.

Use Tkinter Entry Widget in Python set

When you run this code, a window will appear with an Entry widget and a button labeled “Set Name”. Initially, the Entry widget will be empty. Clicking the “Set Name” button will call the set_entry_text() function, which clears any existing text in the Entry widget and sets the text to “John Doe”.

Read Python Tkinter TreeView – How to Use

Tkinter Entry Integer Only

To restrict a Tkinter Entry widget to accept only integer values, you can use the validatecommand option along with a validation function. Here’s a concise example:

import tkinter as tk

def validate_integer(value):
    if value.isdigit():
        return True
    elif value == "":
        return True
    else:
        return False

root = tk.Tk()
root.title("Integer Only Entry Example")

vcmd = (root.register(validate_integer), '%P')
entry = tk.Entry(root, validate='key', validatecommand=vcmd)
entry.pack()

root.mainloop()

When you run this code, the Entry widget will only accept integer values. If the user tries to enter any non-digit character, it will be rejected, and the character will not appear in the Entry widget. The user can still clear the Entry widget by deleting all the characters.

Read Python Tkinter ToDo List

Python Tkinter entry textvariable

A text variable is used to provide value through a variable. value can be Integer or String, for integer: IntVar() keyword is used, for String: StringVar() keyword is used.

from tkinter import * 

ws = Tk()
name = StringVar(ws, value='Michael')
nameTf = Entry(ws, textvariable=name).pack()

ws.mainloop()

In this output, if the user will not provide any information then ‘Michael’ will be taken as the default input’

Read Python Tkinter Window Size

Conclusion

In this tutorial, I explained how to use Tkinter Entry widget in Python. I discussed how to create an entry widget in Python Tkinter, configure entry widget, retrieve user input, validate user input, use entry widgets in forms, display default text, and style entry widgets. I also discussed how to display data in a table using entry widgets, entry set text, entry set value, entry integer only and entry textvariable.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.