登录
首页 >  文章 >  python教程

Tkinter显示图片的完整教程与代码示例

时间:2025-12-24 08:18:45 167浏览 收藏

文章不知道大家是否熟悉?今天我将给大家介绍《Python tkinter显示图片的完整方法如下:导入tkinter和PIL库import tkinter as tk from PIL import Image, ImageTk创建主窗口root = tk.Tk() root.title("图片显示示例")加载图片image = Image.open("your_image.png") # 替换为你的图片路径 photo = ImageTk.PhotoImage(image)创建标签显示图片label = tk.Label(root, image=photo) label.pack()运行主循环root.mainloop()完整代码示例:import tkinter as tk from PIL import Image, ImageTk root = tk.Tk() root.title("图片显示示例") # 加载图片 image = Image.open("example.jpg") photo = ImageTk.PhotoImage(image) # 显示图片 label = tk.Label(root, image=photo) label.pack() root.mainloop()注意事项:确保图片路径正确使用PIL库需要先安装:pip install pillow图片格式支持jpg/png/bmp等常见格式可通过image.resize()调整图片尺寸可添加按钮等控件实现交互功能》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

答案:tkinter中显示图片需用PhotoImage类,原生支持GIF格式;对于JPG、PNG等格式需借助Pillow库的ImageTk.PhotoImage;加载后必须保存引用防止被回收,并可使用Pillow调整大小。

如何用python tkinter插入显示图片?

在 Python 的 tkinter 中显示图片,主要使用 PhotoImage 类。但要注意它只支持 GIFPGM/PPM 格式。如果想显示常见的 JPG、PNG 等格式,需要用 Pillow(PIL)库辅助。

1. 显示 GIF 图片(原生支持)

tkinter 原生支持 GIF,可以直接用 PhotoImage 加载:

import tkinter as tk
from tkinter import PhotoImage
<p>root = tk.Tk()
root.title("显示GIF图片")</p><h1>注意:路径要正确,且图片必须是 .gif 格式</h1><p>img = PhotoImage(file="example.gif")</p><p>label = tk.Label(root, image=img)
label.pack()</p><h1>保持引用,防止被垃圾回收</h1><p>root.image = img</p><p>root.mainloop()
</p>

2. 显示 JPG/PNG 等格式(使用 Pillow)

安装 Pillow:

pip install pillow

然后这样使用:

import tkinter as tk
from PIL import Image, ImageTk
<p>root = tk.Tk()
root.title("显示JPG/PNG图片")</p><h1>打开并转换图片</h1><p>image = Image.open("example.jpg")  # 支持 jpg, png, webp 等
photo = ImageTk.PhotoImage(image)</p><p>label = tk.Label(root, image=photo)
label.pack()</p><h1>保持引用</h1><p>root.image = photo</p><p>root.mainloop()
</p>

3. 调整图片大小

用 Pillow 可以轻松缩放图片:

image = Image.open("example.jpg")
image = image.resize((300, 200))  # 调整为 300x200
photo = ImageTk.PhotoImage(image)

4. 注意事项

  • 一定要保存图片对象的引用(如 root.image = photo),否则会被 Python 回收,界面就看不到图了。
  • 路径错误或格式不支持会报错,确保文件存在且格式正确。
  • 建议统一用 Pillow 的 ImageTk.PhotoImage,兼容性更好。

基本上就这些,不复杂但容易忽略引用问题。

以上就是《Tkinter显示图片的完整教程与代码示例》的详细内容,更多关于Python,Tkinter的资料请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>