Python Forum
How to delete text from a tkinter Text widget? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: How to delete text from a tkinter Text widget? (/thread-10436.html)



How to delete text from a tkinter Text widget? - Tang - May-20-2018

Hey everyone,
I'm a beginner in python and I am trying to create a very very simple text editor (simplified version of microsoft Word for example). I already created the Text zone and the menubar, but I want to set up the commands inside the menu. For example, I want the command "Nouveau" (which means "new" in french) to open a new file. I used the
.delete()
mod from tkinter widgets so this is the code:
import tkinter.filedialog
from tkinter import*

def nouveau():
    text1.delete(1.0,END)
    
def ouvrir():
    file=tkinter.filedialog.askopenfile(mode='r')
    fileContents=file.read()
    text1.delete(1.0,END)
    text1.insert(1.0,fileContents)

def save():
    file=tkinter.filedialog.asksaveasfile(mode='w')
    textoutput=text1.get(1.0,END)
    file.write(textoutput.rstrip())
    file.write('\n')


fenetre=Tk()

menubar=Menu(fenetre)
menu1=Menu(menubar,tearoff=0)
menu1.add_command(label="Nouveau",command=nouveau)
menu1.add_command(label="Ouvrir",command=ouvrir)
menu1.add_command(label="Enregistrer",command=save)
menu1.add_separator()
menu1.add_command(label="Quitter",command=fenetre.quit)
menubar.add_cascade(label="Fichier",menu=menu1)

text1=Text(fenetre, width=100,height=300).pack(side=BOTTOM,padx=30,pady=30)

fenetre.config(menu=menubar)
fenetre.mainloop()
But when I run it and click on the "Nouveau" command in the menu, I get this:

Error:
AttributeError: 'NoneType' object has no attribute 'delete'
Thanks for your help! Big Grin


RE: How to delete text from a tkinter Text widget? - Larz60+ - May-20-2018

text1.delete('1.0', END)
text1.update()
this is what you have now, you may have to update the widget to see