无法将图像与tkinter标签相关联 [英] cannot associate image to tkinter label

查看:230
本文介绍了无法将图像与tkinter标签相关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用tkinter.Label()小部件在tkinter GUI上显示图像.该过程看起来很简单明了,但是此代码不起作用!

I am trying to display an image to a tkinter GUI using tkinter.Label() widget. The procedure seems simple and straightforward, but this code doesn't work!

代码:

import Tkinter as tk
import Image, ImageTk, sys

filename = 'AP_icon.gif'
im = Image.open(filename) # Image is loaded, because the im.show() works

tkim = ImageTk.PhotoImage(im)

root = tk.Tk()

label = tk.Label(root, image = tkim) # Here is the core problem (see text for explanation)
label.image = tkim # This is where we should keep the reference, right?
label.grid (row = 0, column = 0)

tk.Button(root, text = 'quit', command = lambda: sys.exit()).grid(row = 1, column = 1)
root.mainloop()

执行此代码时,它不会编译,并显示错误:

When we execute this code, it doesn't compile, giving an error:

TclError: image "pyimage9" doesn't exist

当我定义没有父级rootlabel时,不会发生编译错误,但是GUI不会显示任何图像!

When I define label without its parent root, No compilation error occurs, but the GUI does not display any image!

任何人都可以找出问题所在吗?

Can anyone identify what could be the issue?

推荐答案

当我们尝试在Ipython中运行以上代码时,会发生此问题.可以通过更改行

This problem happens when we attempt to run the above code in Ipython. And it can be solved by changing the line

root = tk.Tk() to

root = tk.Toplevel()

这篇关于无法将图像与tkinter标签相关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆