简体   繁体   English

Tkinter标签图像变为空白

[英]Tkinter label image turns blank

This code I am writing is supposed to add a picture every time a button is clicked, but after I do more than one the last picture disappears. 我正在编写的这段代码应该在每次单击按钮时添加一张图片,但是当我执行了多次操作后,最后一张图片就会消失。

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()

How should I fix this? 我该如何解决?

The problem is that when you call deal again, the PhotoImage stored in card is replaced by another one, so it is garbage collected and it disappears. 问题在于,当您再次致电deal时,存储在cardPhotoImage被另一card替代,因此被垃圾回收并消失了。 To prevent that, you can create a list of pictures: 为防止这种情况,您可以创建图片列表:

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