[英]tkinter canvas image is not displayed in class
I am trying to display an image in python using the tkinter canvas option. 我正在尝试使用tkinter canvas选项在python中显示图像。 However, if I input it in a class, like below, it doesn't give an error but also doesn't show my image.
但是,如果我在一个类中输入它,如下所示,它不会给出错误,但也不会显示我的图像。 The buttons are displayed correctly though.
尽管按钮显示正确。 Also, if I take the code for generating this image out of the class it works correctly.
另外,如果我从类中取出用于生成此图像的代码,则它可以正常工作。 I can't seem to find out what the problem is.
我似乎无法找出问题所在。
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()
You have to keep a reference to the PhotoImage. 您必须保留对PhotoImage的引用。 This is just and example (you can also use
self.background
instead of c.background
): 这只是一个示例(您也可以使用
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.