Monday, November 18, 2024
Google search engine
HomeLanguagesHow to Set Text of Tkinter Text Widget With a Button?

How to Set Text of Tkinter Text Widget With a Button?

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 the tkinter module
import tkinter
 
# Creating the GUI window.
window = tkinter.Tk()
window.title("Welcome to neveropen")
window.geometry("800x100")
 
# Creating our text widget.
sample_text = tkinter.Entry(window)
sample_text.pack()
 
# Creating the function to set the text
# with the help of button
def set_text_by_button():
 
    # Delete is going to erase anything
    # in the range of 0 and end of file,
    # The respective range given here
    sample_text.delete(0,"end")
     
    # Insert method inserts the text at
    # specified position, Here it is the
    # beginning
    sample_text.insert(0, "Text set by button")
 
# Setting up the button, set_text_by_button()
# is passed as a command
set_up_button = tkinter.Button(window, height=1, width=10, text="Set",
                    command=set_text_by_button)
 
set_up_button.pack()
 
window.mainloop()


Output:

RELATED ARTICLES

Most Popular

Recent Comments