Search code examples
pythontkinterpython-imaging-library

Delete everything whenever I pressed remove button


import tkinter as tk
from tkinter import *
from PIL import ImageTk , Image

X_AXIS = 2
cards = None

def addCards():

    global X_AXIS
    global cards

    img = Image.open("widgetClass\Cards\poker3.png")
    img = img.resize((50 , 70) , Image.ADAPTIVE)
    imgTest = ImageTk.PhotoImage(img)

    cards = tk.Label(
        master=frame,
        image=imgTest
    )

    cards.place(x = X_AXIS , y=20)
    cards.image = imgTest

    X_AXIS += 70

def deleteEverything():
    cards.destroy() # Only execute once

root = tk.Tk()
root.title("Display images")
root.geometry("400x400")
root.resizable(False , False)

frame = tk.Frame(borderwidth=2 , height=100 , highlightbackground="red" , highlightthickness=2)
frame_b = tk.Frame(borderwidth=2 , height=100 , highlightbackground="red" , highlightthickness=2)

label = tk.Label(frame , text="Picture demo")
button = tk.Button(frame_b , text="Add cards" , command=addCards)
remove_button = tk.Button(frame_b , text="Remove" , command=deleteEverything)


frame.pack(fill=X)
frame_b.pack(fill=X)
label.place(x=0 , y=0)
button.place(x=0 , y=0)
remove_button.place(x=0 , y=50)

root.mainloop()

I am trying to remove every images after I have pressed remove button. That means, one click all images deleted

Example,

I pressed three times the add card button , then it display three images on the screen,

My point is , I want to remove all pictures whenever I pressed remove button.

I only manage to remove one image by using destroy method in Tkinter label, but only once , after that no matter how many times I pressed , it has no effect on deleting the images.


Solution

  • Since I don't have your images, I had to clean that bit up from this example, but the idea is that a single card is just a card, and you put them in a list of cards, and when it's time to clean everything up, you go through that list, destroy the cards, and then clear the list:

    import tkinter as tk
    
    cards = []
    
    
    def add_card():
        card = tk.Label(master=frame, text=f"Card {len(cards) + 1}")
        card.place(x=2 + len(cards) * 70, y=20)
        cards.append(card)
    
    
    def clear_cards():
        for card in cards:
            card.destroy()
        cards.clear()
    
    
    root = tk.Tk()
    root.geometry("400x400")
    root.resizable(False, False)
    
    frame = tk.Frame(borderwidth=2, height=100, highlightbackground="red", highlightthickness=2)
    frame_b = tk.Frame(borderwidth=2, height=100, highlightbackground="red", highlightthickness=2)
    
    button = tk.Button(frame_b, text="Add card", command=add_card)
    remove_button = tk.Button(frame_b, text="Remove", command=clear_cards)
    
    frame.pack(fill=tk.X)
    frame_b.pack(fill=tk.X)
    button.place(x=0, y=0)
    remove_button.place(x=0, y=50)
    
    root.mainloop()