How to Set Text of Tkinter Text Widget With a Button?
Last Updated :
23 Nov, 2022
Prerequisite: Python GUI – tkinter
Text Widget is used where a user wants to insert multi-line text fields. In this article, we are going to learn the approaches to set the text inside the text fields of the text widget with the help of a button.
Approach: Using insert and delete method
- Import the Tkinter module.
- Create a GUI window.
- Create our text widget
- Creating the function to set the text with the help of a button. This function contains one insert method and one delete method. The delete method is called first to delete the remaining text inside the text widget. It will delete anything in the given range of 0 to end.
- Then the insert method is called to insert the text we want to push into the text widget. It takes in two parameters, one is the position we want to insert and the second is the desired text we want to set in the form of a string.
- The button is created and the function is parsed as a command inside it.
Below is the implementation of the above approach
Python3
import tkinter
window = tkinter.Tk()
window.title( "Welcome to geeksforgeeks" )
window.geometry( "800x100" )
sample_text = tkinter.Entry(window)
sample_text.pack()
def set_text_by_button():
sample_text.delete( 0 , "end" )
sample_text.insert( 0 , "Text set by button" )
set_up_button = tkinter.Button(window, height = 1 , width = 10 , text = "Set" ,
command = set_text_by_button)
set_up_button.pack()
window.mainloop()
|
Output:
Share your thoughts in the comments
Please Login to comment...