You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Pillow显示图片后代码无限运行的问题求助

解决Pillow.show()关闭窗口后代码持续运行的问题

问题根源

Pillow的show()方法本质是调用系统默认图片查看器(比如Windows的照片应用、macOS的预览、Linux的eog),部分系统中这个外部进程不会在你关闭窗口后自动终止,导致Python主进程一直等待它结束,从而出现代码“无限运行”的假象。

可行解决方案

1. 用Tkinter替代show()(推荐,跨平台)

Tkinter是Python自带的GUI库,用它显示图片可以确保关闭窗口后进程正常退出,无需依赖外部查看器。示例代码:

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

# 你的图片路径列表,根据随机数选择
image_paths = ["image1.jpg", "image2.png", "image3.jpeg"]
random_index = random.randint(0, len(image_paths) - 1)
target_image = image_paths[random_index]

# 创建Tkinter窗口
window = tk.Tk()
window.title("随机图片展示")

# 打开图片并转换为Tkinter兼容格式
with Image.open(target_image) as img:
    tk_image = ImageTk.PhotoImage(img)
    # 用Label显示图片
    image_label = tk.Label(window, image=tk_image)
    image_label.pack()

# 设置关闭窗口时销毁进程
window.protocol("WM_DELETE_WINDOW", window.destroy)

# 启动窗口主循环
window.mainloop()

2. 手动终止系统图片查看器进程(平台相关)

如果坚持要用show(),可以在调用后手动杀掉对应的系统进程,但注意不同系统的进程名不同:

  • Windows(照片应用):
from PIL import Image
import os

with Image.open("test.jpg") as img:
    img.show()
# 强制关闭照片应用进程
os.system("taskkill /f /im Photos.exe")
  • Linux(以eog为例):
from PIL import Image
import os

with Image.open("test.jpg") as img:
    img.show()
os.system("pkill eog")
  • macOS(预览应用):
from PIL import Image
import os

with Image.open("test.jpg") as img:
    img.show()
os.system("pkill Preview")

3. 用subprocess调用查看器并控制子进程

通过subprocess启动图片查看器,手动管理子进程生命周期,关闭后主动终止:

from PIL import Image
import subprocess
import platform
import random

image_paths = ["image1.jpg", "image2.png"]
target_img = image_paths[random.randint(0,1)]

# 根据系统选择查看器
if platform.system() == "Windows":
    viewer = "explorer.exe"
elif platform.system() == "Darwin":
    viewer = "open"
else:
    viewer = "xdg-open"

# 启动子进程打开图片
proc = subprocess.Popen([viewer, target_img])
# 等待用户关闭窗口后结束进程
proc.wait()

内容的提问来源于stack exchange,提问作者ethan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 03:42:18