如何将图像加载到 python 3.4 tkinter 窗口中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35024118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to load an image into a python 3.4 tkinter window?
提问by Luke Gibson
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?
我花了一些时间在网上查找,到目前为止还没有找到任何可以在不使用 PIL 的情况下回答这个问题的内容,我无法开始工作,还有另一种方法可以简单地做到这一点吗?
采纳答案by Bryan Oakley
tkinter has a PhotoImageclass 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.
tkinter有一个PhotoImage类,可用于显示 GIF 图像。如果您想要其他格式(而不是过时的 PGM/PPM 格式),您需要使用 PIL 或 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.
有一个简单的解决方法(保存对图像对象的持久引用),但上述代码的重点是尽可能显示最简单的代码。
For more information see this web page: Why do my Tkinter images not appear?
有关更多信息,请参阅此网页:为什么我的 Tkinter 图像不出现?
回答by Sentekin Can
Luke, this is too late , however may help others. Your image has to be in the same sub directory with .py script. You can also type './imageFileName.png'
卢克,这为时已晚,但可以帮助其他人。您的图像必须与 .py 脚本位于同一子目录中。您也可以输入“./imageFileName.png”