Set Text of Tkinter Text Widget With a Button

Tkinter Text widget doesn’t have a dedicated set method to set the content of the Text. It needs to first delete the existing content and then insert the new content if we have to change the content completely.

This article will introduce how to set the Tkinter widget usinga Tkinter button.

Complete Working Codes to Set Text in Text With delete and insert Methods

import tkinter as tk
root = tk.Tk()
root.geometry("400x240")

def setTextInput(text):
    textExample.delete(1.0,"end")
    textExample.insert(1.0, text)

textExample = tk.Text(root, height=10)
textExample.pack()

btnSet = tk.Button(root, 
                   height=1, 
                   width=10, 
                   text="Set", 
                   command=lambda:setTextInput("new content"))
btnSet.pack()

root.mainloop()

Tkinter Set Content of Tkinter Text_delete and insert method

textExample.delete(1.0,"end")

delete method of Text deletes the specified range of characters in the Text box, as introduced in the article of how to clear Tkinter Text box.

1.0 is the first character and "end" is the last character of the content in the Text widget. Therefore, it deletes all the content inside the Text box.

textExample.insert(1.0, text)

insert method inserts the text at the specified position. In the above code, it inserts the text at the beginning.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Tkinter Text

  • Delete Tkinter Text Box's Contents
  • Make Tkinter Text Widget Read Only