当我使用PhotoImage调用它们时,为什么我的.gif文件会出现?

时间:2015-08-26 06:19:04

标签: python tkinter photoimage

from tkinter import *
from random import *
from functools import partial


class Game:
    def __init__(self):
        self.root = Tk()

        self.frame = Frame(width = 574, height = 574)
        self.frame.grid(columnspan = 30, rowspan = 30)

        self.minex = []
        self.miney = []

        self.clickx = 0
        self.clicky = 0

        blank = PhotoImage(file = 'C:\\Users\\PC\\Desktop\\Python Programs\\Minesweeper\\blank.gif')

        for i in range(0,30):
            for j in range(0,30):
                button = Button(width = 15, height = 15, padx = 2, pady = 2, image = blank, command = partial(self.click, j, i))
                button.grid(row = i, column = j)

        self.mine_place()

        self.root.mainloop()

    def mine_place(self):
        for i in range(0,15):
            self.minex.append(randint(1,30))
            self.miney.append(randint(1,30))

    def click(self, j, i):
        miss = PhotoImage(file = 'C:\\Users\\PC\\Desktop\\Python Programs\\Minesweeper\\miss.gif')
        hit = PhotoImage(file = 'C:\\Users\\PC\\Desktop\\Python Programs\\Minesweeper\\hit.gif')
        for k in range(0, len(self.minex)):
            if j + 1 == self.minex[k] and i + 1 == self.miney[k]:
                button = Button(image = hit)
                button.grid(row = i, column = j)
            else:
                button = Button(image = miss)
                button.grid(row = i, column = j)


app = Game()

在self.click中,当我想创建一个带有此图像的按钮时,我会得到一张空白图像。如果我在 init 中创建一个按钮,图像就会很好。怎么了?.............................................. ................

1 个答案:

答案 0 :(得分:1)

使用PhotoImage后,您需要保存对图像的引用,看起来您的图像正在收集垃圾。

ie - 您创建了图片blank,因此请将参考保存为self.blank = blank并使用image = self.hit