Python Forum

Full Version: How to delete text from a tkinter Text widget?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
text1.delete('1.0', END)
text1.update()
this is what you have now, you may have to update the widget to see