Tkinter(Mac、Python 2.6):使用 create_image 和菜单项时图像不可见
我定义了一个菜单,该菜单应在项目中显示图像(JPG,250x250)。
import Tkinter
from PIL import Image, ImageTk
def show_photo():
img=Image.open("image.jpg")
photo=ImageTk.PhotoImage(img)
width=photo.width();
height=photo.height()
w=Tkinter.Toplevel(root)
w.geometry(str(width+2)+'x'+str(height+2))
w.title(str(width)+'x'+str(height))
canvas=Tkinter.Canvas(w, bg="black", width=width, height=height)
canvas.pack()
img=canvas.create_image(0,0,anchor=Tkinter.NW,image=photo)
xxx # NameError
root=Tkinter.Tk()
mainmenu = Tkinter.Menu(root)
menu1 = Tkinter.Menu(mainmenu)
mainmenu.add_cascade(label="Menu 1", menu=menu1)
menu1.add_command(label="Show photo", command=show_photo)
root.config(menu=mainmenu)
root.mainloop()
除非我放了错误的行(此处:xxx),否则图像不会出现,只有正确大小的黑色矩形。
有什么线索吗?
提前致谢, 埃里克.
I've defined a menu which should show an image (JPG, 250x250) in an item.
import Tkinter
from PIL import Image, ImageTk
def show_photo():
img=Image.open("image.jpg")
photo=ImageTk.PhotoImage(img)
width=photo.width();
height=photo.height()
w=Tkinter.Toplevel(root)
w.geometry(str(width+2)+'x'+str(height+2))
w.title(str(width)+'x'+str(height))
canvas=Tkinter.Canvas(w, bg="black", width=width, height=height)
canvas.pack()
img=canvas.create_image(0,0,anchor=Tkinter.NW,image=photo)
xxx # NameError
root=Tkinter.Tk()
mainmenu = Tkinter.Menu(root)
menu1 = Tkinter.Menu(mainmenu)
mainmenu.add_cascade(label="Menu 1", menu=menu1)
menu1.add_command(label="Show photo", command=show_photo)
root.config(menu=mainmenu)
root.mainloop()
Unless I put a wrong line (here: xxx), the image doesn't appear, only a correct size black rectangle.
Any clue ?
Thanks by advance,
Eric.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的猜测是:你的图像位于局部变量中。当
show_photo()
退出时,图像引用将被垃圾收集,从而图像被销毁。当这种情况发生时,Tkinter 不再能够显示图像,因为数据消失了。尝试在全局变量或实例变量中保存对图像的引用。
My guess is this: your image is in a local variable. When
show_photo()
exits, the image reference gets garbage-collected and thus the image gets destroyed. When that happens Tkinter is no longer able to show the image because the data is gone.Try saving a reference to the image, either in a global or instance variable.