Search code examples
pythonfor-looptkintertkinter-entry

I need to clear a Entry widget in tkinter after press a button


I have a code that creates 10 entries using a for loop, which saves the result in a list so I can use get, but I have another button and I need to delete what is written in the 10 entries, how do I do that?

    for i in range(10):
        entry = Entry(self.lf_mid)
        entry.place(relwidth=0.6, relheight=1/10, relx=0.35, rely=i/10)
        lista_entrys.append(entry)
    
    #this don't work
    bt = Button(self.lf_bot, text='clear', command=entry.delete(0, 'end'))
    bt.pack(side='left', expand=1)

I appreciate if you can help me <3


Solution

  • make a widget dictionary that you add to every time you create a widget. Then wherever you want to access the widget, for example if you want to destroy it or change its configuration attributes, you do this through the dictionary.

    Skeleton of the idea:

    import tkinter as tk
    widgetdict = {}
    def maketk():
        root = tk.Tk()
        entry = tk.Entry()
        widgetdict['entry'] = entry
        root.mainloop()
    
    maketk()
    widgetdict['entry']['bg'] = '#fff'
    widgetdict['entry'].destroy()
    

    What goes into the dictionary is the pointer/address of the entry. So long as you haven't already destroyed the widget somewhere else then you have access.