提问人:Chee Hong 提问时间:11/13/2023 更新时间:11/13/2023 访问量:23
每当我按下删除按钮时删除所有内容
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()
按下删除按钮后,我正在尝试删除所有图像。这意味着,一键删除所有图像
例
我按了三次添加卡按钮,然后它在屏幕上显示三张图像,
我的观点是,每当我按下删除按钮时,我都想删除所有图片。
我只能使用 Tkinter 标签中的 destroy 方法删除一个图像,但只有一次,之后无论我按多少次,它都对删除图像没有影响。
答:
0赞
AKX
11/13/2023
#1
由于我没有你的图像,我不得不从这个例子中清理这一点,但这个想法是,一张卡只是一个 ,你把它们放在一个列表中,当需要清理所有内容时,你浏览该列表,销毁 s,然后清除列表: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()
评论
cards