【问题标题】:How to open an image in Python and close afterwards?如何在 Python 中打开图像然后关闭?
【发布时间】:2021-10-14 20:17:35
【问题描述】:

Python 版本:3.7.9

我尝试过将 Pillow/PIL 与 show() 和 close() 一起使用,但这只会关闭命令提示符并让文件查看器保持打开状态。

我已经尝试过子进程 Popen,但即使文件是正确的,它也只会给我错误“系统找不到指定的文件”。所以我现在只是卡住了。我认为这对于 Python 来说是一个简单的过程。

我只是想打开一张图片,然后在用户点击一个按钮后,就可以关闭它。

对建议/库开放。谢谢!

【问题讨论】:

标签: python image subprocess python-imaging-library


【解决方案1】:

只需调用此函数,就会弹出一个带有图像的新窗口。 在窗口关闭之前,您的代码不会被执行。

import tkinter
from PIL import ImageTk, Image

def image_preview (path, size = (0, 0)):
    root = tkinter.Tk ()#Start window
    root.title ("Preview")#Modify this to change the title
    rawimg = Image.open(path)#Open image path

    if size != (0, 0):#If a specific resolution has been requested
        rawimg = rawimg.resize (size)#Change the image resolution

    img = ImageTk.PhotoImage(rawimg)#Adapt the image to tkinter
    panel = tkinter.Label (root, image = img)#Add image to the window
    panel.pack ()#Build window
    root.mainloop ()#Run window

使用示例行:

image_preview ("image.png", (500, 500))#With specified resolution
image_preview ("image.png")#Use the image resolution

【讨论】:

  • 我试过了,它确实打开了图像,但是它打开它非常放大了哈哈
  • 我已经更新了答案,现在您可以将分辨率作为元组传递给函数。指定的分辨率将是图像和窗口的大小。我还添加了 cmets。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-01
  • 1970-01-01
  • 2015-10-23
  • 2010-09-27
  • 2023-01-12
相关资源
最近更新 更多