7

我正在尝试使用 tkinter 画布选项在 python 中显示图像。但是,如果我在一个类中输入它,如下所示,它不会给出错误但也不会显示我的图像。但按钮显示正确。此外,如果我将生成此图像的代码从类中取出,它可以正常工作。我似乎无法找出问题所在。

import Tkinter as tk
from Tkinter import *

class Board(tk.Frame):
    def __init__(self,parent):

        frame = Frame(parent)
        frame.pack()
        tk.Frame.__init__(self,parent)

        frame2 = Frame(frame)
        frame2.pack()

        c=Canvas(frame2)
        c.pack(expand=YES,fill=BOTH)
        background=PhotoImage(file='Board.gif')
        c.create_image(100,100,image=background,anchor='nw')

        button = Button(frame, text="Next turn", command=self.next_turn)
        button.pack()

        button = Button(frame, text="Roll the dice", command=self.roll)
        button.pack()

        ....

root = Tk()
board = Board(root)
board.pack()
root.mainloop()
4

1 回答 1

8

您必须保留对 PhotoImage 的引用。这只是示例(您也可以使用self.background代替c.background):

    c = Canvas(frame2)
    c.pack(expand=YES,fill=BOTH)
    c.background = PhotoImage(file='Board.gif')
    c.create_image(100,100,image=c.background,anchor='nw')
于 2013-05-30T22:00:16.203 回答