Tkinter Entry Widget

Tkinter Entry Widget

In this tutorial, you’ll learn how to use the Tkinter Entry widget to create a textbox for user input.

Introduction to Tkinter Entry Widget

The Entry widget allows you to enter a single line of text. To create a textbox in Tkinter, you use the following syntax:

textbox = ttk.Entry(master, **options)
Code copied!

In this syntax:

  • master: The parent frame or window where you want to place the widget.
  • options: One or more keyword arguments used to configure the Entry widget.

If you want to enter multi-line text, consider using the Text widget instead.

Getting Text from the Entry Widget

To retrieve the current text from an Entry widget, use the get() method:

current_text = textbox.get()
Code copied!

Using StringVar with Entry Widget

Typically, you associate the current value of the textbox with a StringVar object:

text = tk.StringVar()
textbox = ttk.Entry(root, textvariable=text)
Code copied!

This allows you to retrieve the value using:

text_value = text.get()
Code copied!

Setting Focus to the Entry Widget

To enhance user experience, you can set focus to the first Entry widget when the window appears:

textbox.focus()
Code copied!

Creating a Password Entry

To hide sensitive information, such as passwords, you can use the show option:

password = tk.StringVar()
password_entry = ttk.Entry(root, textvariable=password, show='*')
Code copied!

Example: Sign-In Form

The following program demonstrates how to create a sign-in form using Entry widgets:

import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo

root = tk.Tk()
root.geometry("300x150")
root.title('Sign In')

email = tk.StringVar()
password = tk.StringVar()

def login_clicked():
    msg = f'Email: {email.get()} | Password: {password.get()}'
    showinfo(title='Information', message=msg)

signin = ttk.Frame(root)
signin.pack(padx=10, pady=10, fill='x', expand=True)

email_label = ttk.Label(signin, text="Email Address:")
email_label.pack(fill='x', expand=True)

email_entry = ttk.Entry(signin, textvariable=email)
email_entry.pack(fill='x', expand=True)
email_entry.focus()

password_label = ttk.Label(signin, text="Password:")
password_label.pack(fill='x', expand=True)

password_entry = ttk.Entry(signin, textvariable=password, show="*")
password_entry.pack(fill='x', expand=True)

login_button = ttk.Button(signin, text="Login", command=login_clicked)
login_button.pack(fill='x', expand=True, pady=10)

root.mainloop()
Code copied!

Conclusion

In this tutorial, you learned how to effectively use the Tkinter Entry widget to create text input fields:

  • Use the ttk.Entry widget to create a textbox.
  • Utilize StringVar to manage the current text value.
  • Implement the show option to create password fields.

These techniques enhance user interaction and improve the overall functionality of your Tkinter applications.