I have basically a similar question, though I do not feel it has been answered properly:
Tkinter: How can I dynamically create a widget that can then be destroyed or removed?
The accepted answer is:
You'll want to store the dynamically-created widgets in a list. Have something like
dynamic_buttons = [] def onDoubleClick(event): ... button = Button(...) dynamic_buttons.append(button) button.pack() You can then access the buttons for removal with, say, dynamic_buttons[0].destroy()
You can see that the reference they speak of is not variable, here the number 0 is used. But when dynamically creating widgets, how do you connect these references to the buttons?
Say that you create a Toplevel widget (displays a file's content), and want to have a button to close the widget. The dynamic creation will allow multiple files to be open. The problem is that even with this list, how will the button "know" to which widget it belongs, as there is no hard reference (great that you have a list of the items, but toplevel 5 + button 5 have no clue they are 5th in their lists). There will always be just one "active" version of the button and the toplevel, and this one can be deleted.
aanstuur_files = []
aanstuur_frames = []
aanstuur_buttons = []
def editAanstuur():
openfiles = filedialog.askopenfilenames()
if not openfiles:
return
for file in openfiles:
newtop = Toplevel(nGui, height=100, width=100)
labelTitle = Label(newtop, text=file).pack()
newButton = Button(newtop, text="save & close", command= ...).pack()
aanstuur_files.append(file)
aanstuur_buttons.append(newButton)
aanstuur_frames.append(newtop)