类中未显示 tkinter 画布图像 [英] tkinter canvas image is not displayed in class
本文介绍了类中未显示 tkinter 画布图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 tkinter 画布选项在 python 中显示图像.但是,如果我在类中输入它,如下所示,它不会给出错误,也不会显示我的图像.虽然按钮显示正确.另外,如果我从类中取出用于生成此图像的代码,它可以正常工作.我似乎无法找出问题所在.
I am trying to display an image in python using the tkinter canvas option. 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()
推荐答案
您必须保留对 PhotoImage 的引用.这只是一个例子(你也可以使用 self.background
而不是 c.background
):
You have to keep a reference to the PhotoImage. This is just and example (you can also use self.background
instead of 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')
这篇关于类中未显示 tkinter 画布图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文