The Entry
widget in Tkinter is a fundamental component for creating GUI applications that require text input from the user.
It allows users to type and edit single-line strings and is commonly used in forms, login interfaces, and data-entry systems.
This guide will walk you through the purpose, syntax, configuration, and practical examples of using the Entry widget effectively in Python.
What is the Tkinter Entry Widget?
The Entry widget is part of the standard Tkinter GUI toolkit and provides a simple yet powerful way to collect a line of text from the user.
Whether you’re asking for a username, email address, or a search query, the Entry widget is typically the go-to solution.
Basic Syntax
entry = tk.Entry(parent, options)
Here, parent
is the container (such as the main window or a frame), and options
can be used to customize the widget’s appearance and behavior.
Common options include:
width
: Specifies the width in characters.font
: Sets the font of the text.textvariable
: Binds the widget to aStringVar
for easier variable handling.show
: Replaces entered text with a character (e.g.,*
) for password fields.
Creating a Simple Entry Widget
import tkinter as tk
root = tk.Tk()
root.title("Simple Entry Example")
entry = tk.Entry(root, width=30)
entry.pack(padx=10, pady=10)
root.mainloop()
This example creates a basic window with a single Entry widget. It accepts text input and displays it on the screen, though it doesn’t yet retrieve or process that input.
Retrieving Text from Entry
To get the current text entered by the user, use the get()
method:
value = entry.get()
Here’s a more complete example:
import tkinter as tk
def get_input():
value = entry.get()
print("You entered:", value)
root = tk.Tk()
root.title("Get Entry Example")
tk.Label(root, text="Enter something:").pack()
entry = tk.Entry(root, width=30)
entry.pack()
tk.Button(root, text="Submit", command=get_input).pack()
root.mainloop()
Inserting and Deleting Text
You can programmatically add or remove text using insert()
and delete()
:
entry.insert(index, text)
— inserts text at a given index (e.g.,0
for the beginning).entry.delete(start, end)
— deletes characters between start and end positions.
entry.insert(0, "Default Text")
entry.delete(0, tk.END)
Using StringVar with Entry
Binding the Entry widget to a StringVar()
makes it easier to work with the input and react to changes in real time.
import tkinter as tk
root = tk.Tk()
var = tk.StringVar()
entry = tk.Entry(root, textvariable=var)
entry.pack()
def show_text():
print("Current value:", var.get())
tk.Button(root, text="Show", command=show_text).pack()
root.mainloop()
Password Input with Entry
You can mask the text input using the show
option. This is useful for password fields.
entry = tk.Entry(root, show="*")