2017-09-14 253 views
0

我編寫的這段代碼應該每次點擊一個按鈕時都會添加一張圖片,但是當我做了不止一次後,最後一張圖片消失了。Tkinter標籤圖像變爲空白

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

我該如何解決這個問題?

回答

0

問題是,當您再次撥打deal時,存儲在card中的PhotoImage被替換爲另一個,因此它被垃圾收集並且它消失。爲了防止這種情況,您可以創建一個圖片列表:

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