You create strings like "idn0.delete(0,END)"
but for Python it is only string, nothing more. It will not run it as command. You would need to use eval("idn0.delete(0,END)")
to execute command in this string but eval()
is not preferred method.
You should keep widgets on list or in dictionary and then you can use for
-loop to delete all items.
But firt other very common mistake
Using
variable = Widget().grid()
you assign None
to variable
because grid()
/pack()
/place()
return None
You have to do it in two steps
variable = Widget()
variable.grid()
Minimal working code
import tkinter as tk # PEP8: `import *` is not preferred
# --- functions ---
def deleteme():
for item in widgets:
item.delete(0, 'end')
# --- main ---
widgets = []
root = tk.Tk()
for number in range(5):
variable = tk.Entry(root)
variable.grid(row=number, column=1)
widgets.append(variable)
btn1 = tk.Button(root, text='Delete', command=deleteme) # PEP8: inside `()` use space after comma `,` but without spaces around `=`
btn1.grid(row=5, column=1)
root.mainloop()
The same with dictionary
import tkinter as tk # PEP8: `import *` is not preferred
# --- functions ---
def deleteme():
for name, item in widgets.items():
item.delete(0, 'end')
# --- main ---
widgets = {}
root = tk.Tk()
for number in range(1, 6):
variable = tk.Entry(root)
variable.grid(row=number, column=1)
widgets[f"idn{number}"] = variable
btn1 = tk.Button(root, text='Delete', command=deleteme) # PEP8: inside `()` use space after comma `,` but without spaces around `=`
btn1.grid(row=5, column=1)
root.mainloop()
Of course you can add widgets manually without for
-loop but this it is long and boring so I skip some widgets. But even if I skip or add widgets I don't have to change code in deleteme()
import tkinter as tk # PEP8: `import *` is not preferred
# --- functions ---
def deleteme():
for name, item in widgets.items():
item.delete(0, 'end')
# --- main ---
widgets = {}
root = tk.Tk()
variable = tk.Entry(root)
variable.grid(row=0, column=1)
widgets["idn1"] = variable
# or
widgets["idn2"] = tk.Entry(root)
widgets["idn2"].grid(row=1, column=1)
widgets["idn3"] = tk.Entry(root)
widgets["idn3"].grid(row=2, column=1)
# etc.
btn1 = tk.Button(root, text='Delete', command=deleteme) # PEP8: inside `()` use space after comma `,` but without spaces around `=`
btn1.grid(row=5, column=1)
root.mainloop()