How to Set the Default Text of Tkinter Entry Widget?
The Tkinter Entry widget is a simple input field in Python that lets users type or edit text. By default, it starts empty unless given an initial value. Adding default text improves user experience by acting as a hint, pre-filling known details and reducing repetitive typing in forms. Let's explore different methods to achieve this.
Using StringVar()
StringVar() is a Tkinter class used to manage text-based variables dynamically. It allows binding a variable to the Entry widget so that changes in the variable automatically reflect in the widget. By assigning a default value while creating StringVar, we can ensure that the input field starts with predefined text.
import tkinter as tk
root = tk.Tk()
root.geometry("300x150")
var = tk.StringVar(value="Hello Geeks") # Default text
tk.Entry(root, textvariable=var).pack(pady=10) # Input field
root.mainloop()
Output:

Explanation: This code initializes a Tkinter window, sets its size and creates a StringVar to store text. It then creates an entry field (Entry) bound to this variable, ensuring dynamic text updates. pack() method arranges the widget with padding and mainloop() starts the GUI event loop.
Using insert()
insert() method allows inserting text at a specified index within the Entry widget. This method is a direct way to add default text without requiring a separate variable. It is useful when we need to pre-fill input fields with placeholder values that users can modify or overwrite.
import tkinter as tk
root = tk.Tk()
root.geometry("300x150")
entry = tk.Entry(root)
entry.insert(0, "Hello Geeks") # Set default text
entry.pack(pady=10) # Add padding
root.mainloop()
Output:

Explanation: insert(0, "hlo geeks") method sets a default text at the beginning (index 0) of the entry field. The pack(pady=10) method adds vertical padding for spacing. Finally, mainloop() starts the GUI event loop to keep the window active.
Using state='readonly'
If we want to display a default value without allowing users to modify it, we can set the state attribute to readonly. This method is particularly useful when we need to display non-editable information, such as predefined values or system-generated outputs, that should remain unchanged by users.
import tkinter as tk
root = tk.Tk()
root.geometry("300x150")
var = tk.StringVar(value="Hello Geeks") # Default text
tk.Entry(root, textvariable=var, state="readonly").pack(pady=10) # Read-only input
root.mainloop()
Output:

Explanation: This method binds a StringVar to the Entry widget with state='readonly', making the text non-editable. It’s useful for displaying static, predefined values. The pack(pady=10) adds padding and root.mainloop() ensures the window stays open.