Python编程实例-Tkinter GUI编程-PhotoImage

PhotoImage
在本文中,将介绍如何使用 Tkinter PhotoImage 小部件在另一个小部件上显示图像。

1、PhotoImage介绍
在 Tkinter 中,一些小部件可以显示图像,例如 Label 和 Button。 这些小部件采用允许它们显示图像的图像参数。但是,不能简单地将图像文件的路径传递给 image 参数。 相反,需要创建一个 PhotoImage 对象并将图像参数传递给它。要创建新的 PhotoImage 对象,请使用以下语法:

photo_image = tk.PhotoImage(file=path_to_image)
1
在此语法中,将图像的路径传递给文件参数以创建新的 PhotoImage 对象。或者,将包含图像数据的字节对象传递给 data 参数。创建 PhotoImage 对象后,可以在其他接受图像参数的小部件中使用它:

label = ttk.Label(root, image=photo_image)
1
请务必注意,只要图像将显示,对 PhotoImage 对象的引用就会保持在范围内。 否则,图像不会出现。

以下示例尝试在根窗口上显示路径为“./assets/python.png”的图像:

import tkinter as tk
from tkinter import ttk


class App(tk.Tk):
def __init__(self):
super().__init__()
python_image = tk.PhotoImage(file='./assets/python.png')
ttk.Label(self, image=python_image).pack()


if __name__ == "__main__":
app = App()
app.mainloop()

如果你运行程序,你会注意到窗口没有显示图像。为什么?

这是因为一旦 __init__() 结束,python_image 就会被销毁。 由于程序没有引用 PhotoImage 对象,因此即使已将其打包到布局中,图像也会消失。

要解决此问题,需要确保在__init__()方法结束后 python_image 不会超出范围。 例如,可以将其保存在 App 类的实例中,例如 self.python_image:

2、完整示例
目前,PhotoImage 小部件支持 GIF、PGM、PPM 和 PNG 文件格式。要支持 JPG、JPEG 或 BMP 等其他文件格式,可以使用 Pillow 等图像库将它们转换为 PhotoImage 小部件可以理解的格式。

事实上,Pillow 库在 PIL.ImageTk 模块中有一个与 Tkinter 兼容的 PhotoImage 小部件。

以下 pip 命令安装 Pillow 库:

pip install Pillow
1
要使用 Pillow 库,请执行以下步骤:

第一步,导入 Image 和 ImageTk 类:

from PIL import Image, ImageTk
1
第二步,打开图片文件,新建一个PhotoImage对象:

image = Image.open('./assets/python.jpg')
python_image = ImageTk.PhotoImage(image)
1
2
第三步,将 ImageTk.PhotoImage 对象分配给 image 选项:

image_label = ttk.Label(root, image=python_image)
1
以下代码演示了如何使用 Pillow 库中的 PhotoImage 小部件:

import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk


class App(tk.Tk):
def __init__(self):
super().__init__()
self.title('Tkinter PhotoImage Demo')

self.image = Image.open('./assets/python.jpg')
self.python_image = ImageTk.PhotoImage(self.image)

ttk.Label(self, image=self.python_image).pack()


if __name__ == '__main__':
app = App()
app.mainloop()
————————————————
版权声明:本文为CSDN博主「视觉智能」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wujuxKkoolerter/article/details/124291814

posted @ 2022-06-17 15:59  苍月代表我  阅读(2886)  评论(0)    收藏  举报