如何在python中添加图片_如何在Tkinter中添加图片?

根据文件path指向的格式,您的实际代码可能会返回错误。也就是说,PhotoImage类已经支持一些图像格式,例如.gif,.pgm(和.png,如果tk.TkVersion> = 8.6)。

下面是显示一个例子:

,或者如果tk.TkVersion < 8.6:

try: # In order to be able to import tkinter for

import tkinter as tk # either in python 2 or in python 3

except ImportError:

import Tkinter as tk

def download_images():

# In order to fetch the image online

try:

import urllib.request as url

except ImportError:

import urllib as url

url.urlretrieve("https://i.stack.imgur.com/IgD2r.png", "lenna.png")

url.urlretrieve("https://i.stack.imgur.com/sML82.gif", "lenna.gif")

if __name__ == '__main__':

download_images()

root = tk.Tk()

widget = tk.Label(root, compound='top')

widget.lenna_image_png = tk.PhotoImage(file="lenna.png")

widget.lenna_image_gif = tk.PhotoImage(file="lenna.gif")

try:

widget['text'] = "Lenna.png"

widget['image'] = widget.lenna_image_png

except:

widget['text'] = "Lenna.gif"

widget['image'] = widget.lenna_image_gif

widget.pack()

root.mainloop()

你可能感兴趣的:(如何在python中添加图片)