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()
按下删除按钮后,我试图删除所有图像。也就是说,一键删除所有图片
例如,
我按了三下添加卡按钮,然后屏幕上显示了三个图像,
我的观点是,每当我按下删除按钮时,我想删除所有图片。
我只使用Tkinter标签中的destroy方法删除了一张图像,但只删除了一次,之后无论我按多少次,都对删除图像没有影响。
因为我没有你的图像,所以我必须从这个例子中清理掉这一点,但这个想法是一张卡片只是一个
card
,你把它们放在cards
的列表中,当是时候清理所有内容了,您浏览该列表,销毁 card
,然后清除列表:
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()