繁体   English   中英

Tkinter标签图像变为空白

[英]Tkinter label image turns blank

我正在编写的这段代码应该在每次单击按钮时添加一张图片,但是当我执行了多次操作后,最后一张图片就会消失。

import tkinter

suits = ["club", "heart", "diamond", "spade"]
faces = ["jack", "queen", "king"]


def deal():
    global value
    global card
    global deck
    value, card = deck.pop(0)
    print(deck)
    return card

def image():
    global count
    tkinter.Label(root, image=deal()).grid(row=1, column=count)
    count += 1

root = tkinter.Tk()

deck = []

for x in range(1, 11):
    for y in suits:
        pic = "cards/{}_{}.png".format(x, y)
        img = tkinter.PhotoImage(file=pic)
        deck.append((x, img))

    for z in faces:
        pic = "cards/{}_{}.png".format(z, y)
        img = tkinter.PhotoImage(file=pic)
        deck.append((10, img))

value, card = deck.pop(0)
count = 0

tkinter.Button(root, text="Click me", command=image).grid(row=0, column=0)
root.mainloop()

我该如何解决?

问题在于,当您再次致电deal时,存储在cardPhotoImage被另一card替代,因此被垃圾回收并消失了。 为防止这种情况,您可以创建图片列表:

import tkinter

suits = ["club", "heart", "diamond", "spade"]
faces = ["jack", "queen", "king"]
pictures = []

def deal():
    global value
    global card
    global deck
    value, card = deck.pop(0)
    print(deck)
    return card

def image():
    global count
    tkinter.Label(root, image=deal()).grid(row=1, column=count)
    count += 1

root = tkinter.Tk()

deck = []

for x in range(1, 11):
    for y in suits:
        pic = "cards/{}_{}.png".format(x, y)
        img = tkinter.PhotoImage(file=pic)
        pictures.append(img)
        deck.append((x, img))

    for z in faces:
        pic = "cards/{}_{}.png".format(z, y)
        img = tkinter.PhotoImage(file=pic)
        pictures.append(img)
        deck.append((10, img))

value, card = deck.pop(0)
count = 0

tkinter.Button(root, text="Click me", command=image).grid(row=0, column=0)
root.mainloop()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM