How to erase everything from the Tkinter text widget?


Tkinter Text widget accepts and supports multiline user input. We can specify other properties of the Text Widget such as the width, height, background, border-width, and other properties as well.

Let us suppose that we want to erase all the content in the given Text widget; then, we can use the delete("1.0", END) function.

Example

In this example, we will insert some random text using random module in Python and erase using the delete() method.

#Import the required Libraries
from tkinter import *
from tkinter import ttk
import random

#Create an instance of Tkinter frame
win = Tk()

#Set the geometry of Tkinter Frame
win.geometry("750x250")

#Define functions to insert/erase the text
def insert_text():
   text.insert(INSERT,chr(random.randint(ord('a'),ord('z'))))

def erase_text():
   text.delete("1.0",END)

#Create a Text widget
text= Text(win, width=50, height= 5)
text.focus_set()
text.pack()

#Add a bottom widgets
button1= ttk.Button(win, text= "Insert",command= insert_text)
button1.pack(side=TOP)
button2= ttk.Button(win, text= "Erase",command= erase_text)
button2.pack(side=TOP)
#Create a Button widget
win.mainloop()

Output

Run the above code to display a window that contains a text widget and buttons to erase all the content of it.

Now, click the "Insert" Button to insert some random character in the Text Box. Once the characters are inserted in the text box we can erase all the content by clicking on the button "Erase".

Updated on: 04-May-2021

266 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements