'creating a reverse function

So I have created a button that will display 3 more buttons how I want it but I want to know if there is a fast easy way to make a button that can basically undo that function to make the 3 created buttons disappear

def show_pictures():
    x =0
    while x != 3:
        x += 1
        testImage = PhotoImage(file = "C:/Users/harry/Documents/coursework/images/test.png")
        imagesize = testImage.subsample(4, 3)
        Button(main_window, image= imagesize,).grid()

showButton = Button(main_window, text="Show Friend's Pictures", command= show_pictures)
showButton.grid(row=0, column=0)
clearButton = Button(main_window, text="Clear Pictures", command= show_pictures)
clearButton.grid(row=0, column=1, padx=5)


Solution 1:[1]

Simply use a list to store the buttons, then it is easy to destroy those buttons using the list:

buttons = [] # list to store buttons

def show_pictures():
    testImage = PhotoImage(file="C:/Users/harry/Documents/coursework/images/test.png")
    imagesize = testImage.subsample(4, 3)
    for x in range(3):
        btn = Button(main_window, image=imagesize)
        btn.grid()
        btn.image = imagesize # save reference of image to prevent from garbage collected
        buttons.append(btn) # store button to list

def clear_pictures():
    # destroy all buttons in list
    for btn in buttons:
        btn.destroy()
    # clear the button list
    buttons.clear()

showButton = Button(main_window, text="Show Friend's Pictures", command=show_pictures)
showButton.grid(row=0, column=0)
clearButton = Button(main_window, text="Clear Pictures", command=clear_pictures)
clearButton.grid(row=0, column=1, padx=5)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 acw1668