I have made a Tkinter UI for a fairly simple calculator that all works fine, and I have a clear button to clear all entry boxes. I’d rather have one line of code to clear all 40+ boxes than 40+ lines to clear each individually, and was wondering if there was a Tkinter command that could do the same as ent.delete(0, END)
but for all entries?
Advertisement
Answer
This should be sufficient:
[widget.delete(0, tk.END) for widget in root.winfo_children() if isinstance(widget, tk.Entry)]
It uses list comprehension to loop through all the children of root and does .delete()
if the child is an Entry
Implementation:
import tkinter as tk
root = tk.Tk()
root.geometry("300x300")
def create_entries(root, amount):
for _ in range(amount):
tk.Entry(root).pack(pady=2)
def clear():
[widget.delete(0, tk.END) for widget in root.winfo_children() if isinstance(widget, tk.Entry)]
create_entries(root, 5)
clear_btn = tk.Button(root, text="clear", padx=10, command=clear)
clear_btn.pack()
root.mainloop()
NOTE:
I should point out that this is probably not best practice but I dont really know.
It creates a list but doesnt assign it to anything so essentially it just does what you intended
EDIT:
Also consider the following if you want to clear every entry, even if it is inside a different widget. This is to be used only if you are sure that every single entry in the whole application should be cleared
def clear(root):
for widget in root.winfo_children():
if not isinstance(widget, tk.Entry):
clear(widget)
elif isinstance(widget, tk.Entry):
widget.delete(0, tk.END)
Also note that, I used a normal for loop for this, because as noted in the comments, it is better