The Tkinter Entry widget does not have any text attribute that can be used to set the default text. Therefore, default text must be added to any text field in Tkinter using the following methods:
- Insert method
- stringvar method
Method 1: Using the insert method
The tkinter module is imported. The root widget is created and this must be done before creating any other widget. The dimension of the root widget is specified 200×100 . Next a Entry widget ‘textBox ‘ is created on the root widget. The insert() method is called on the Entry widget. The insert() method takes two arguments. The first argument is the position of the string and the second argument is the text itself. Since the text must be there by default in the Entry widget, the position of the text is set to 0. Finally, the pack() method is called on the Entry widget and it positions it on the root widget. The root.mainloop() helps to run the application.
Below is the implementation:
Python3
import tkinter as tk root = tk.Tk() root.geometry( "200x100" ) textBox = tk.Entry(root) textBox.insert( 0 , "This is the default text" ) textBox.pack() root.mainloop() |
Output
Method 2: Using the stringvar method
The second method to add a default text to the Entry widget in Tkinter is the StringVar() method. The tkinter module is imported. The root widget is created and this must be done before creating any other widget. The dimension of the root widget is specified 200×100 . A text variable is a string variable and is its value is set to the default text. Next, an Entry widget ‘textBox ‘ is created on the root widget. The textvariable attribute of the Entry widget is assigned the value of the text variable. Finally, the pack() method is called on the Entry widget and it positions it on the root widget. The root.mainloop() helps to run the application.
Below is the implementation:
Python3
import tkinter as tk root = tk.Tk() root.geometry( "200x100" ) text = tk.StringVar() text. set ( "This is the default text" ) textBox = tk.Entry(root,textvariable = text) textBox.pack() root.mainloop() |
Output