如何将图像加载到python 3.4 tkinter窗口中? [英] How to load an image into a python 3.4 tkinter window?

查看:82
本文介绍了如何将图像加载到python 3.4 tkinter窗口中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了一些时间在网上寻找信息,到目前为止,没有找到任何不使用PIL就能解决此问题的方法,这是我无法工作的,还有其他方法可以简单地做到这一点吗?

I've spent some time looking online and so far haven't found anything that answers this without using PIL, which i can't get to work is there another way to do this simply?

推荐答案

tkinter具有 PhotoImage 可用于显示GIF图像的类.如果您想要其他格式(过时的PGM/PPM格式除外),则需要使用PIL或Pillow之类的东西.

tkinter has a PhotoImage class which can be used to display GIF images. If you want other formats (other than the rather outdated PGM/PPM formats) you'll need to use something like PIL or Pillow.

import Tkinter as tk

root = tk.Tk()
image = tk.PhotoImage(file="myfile.gif")
label = tk.Label(image=image)
label.pack()
root.mainloop()

请务必注意,如果将此代码移入函数中,可能会遇到问题.上面的代码有效,因为它在全局范围内运行.使用函数时,函数退出时图像对象可能会被垃圾回收,这将导致标签显示为空白.

It's important to note that if you move this code into a function, you may have problems. The above code works because it runs in the global scope. With a function the image object may get garbage-collected when the function exits, which will cause the label to appear blank.

有一个简单的解决方法(保存对图像对象的持久引用),但是以上代码的要点是显示尽可能简单的代码.

There's an easy workaround (save a persistent reference to the image object), but the point of the above code is to show the simplest code possible.

有关更多信息,请参见以下网页:为什么我的Tkinter图片没有出现?

For more information see this web page: Why do my Tkinter images not appear?

这篇关于如何将图像加载到python 3.4 tkinter窗口中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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