我可以用PIL以全屏模式显示图像吗?

2024-09-27 07:25:54 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用Python图像库全屏显示图像?

from PIL import Image

img1 = Image.open ('colagem3.png');
img1.show ();

全屏显示!


Tags: from图像imageimportpilpngshowopen
1条回答
网友
1楼 · 发布于 2024-09-27 07:25:54

问题的核心

PIL没有全屏打开图像的本地方法。这是有道理的,它不能。PIL所做的只是在默认的文件查看程序中打开您的文件(通常,Windows上的Windows照片[尽管这取决于Windows版本])。为了全屏打开程序,PIL需要知道发送程序的参数。没有标准的语法。因此,这是不可能的。

但是,这并不意味着没有办法在全屏中打开图像。通过使用Python中的本地库Tkinter,我们可以创建自己的窗口,该窗口以全屏显示图像。

相容性

为了避免系统依赖(直接调用.dll和.exe文件)。这可以通过Tkinter实现。Tkinter是一个显示库。这段代码在任何运行Python2或3的计算机上都能很好地工作。


我们的职能

import sys
if sys.version_info[0] == 2:  # the tkinter library changed it's name from Python 2 to 3.
    import Tkinter
    tkinter = Tkinter #I decided to use a library reference to avoid potential naming conflicts with people's programs.
else:
    import tkinter
from PIL import Image, ImageTk

def showPIL(pilImage):
    root = tkinter.Tk()
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    root.overrideredirect(1)
    root.geometry("%dx%d+0+0" % (w, h))
    root.focus_set()    
    root.bind("<Escape>", lambda e: (e.widget.withdraw(), e.widget.quit()))
    canvas = tkinter.Canvas(root,width=w,height=h)
    canvas.pack()
    canvas.configure(background='black')
    imgWidth, imgHeight = pilImage.size
    if imgWidth > w or imgHeight > h:
        ratio = min(w/imgWidth, h/imgHeight)
        imgWidth = int(imgWidth*ratio)
        imgHeight = int(imgHeight*ratio)
        pilImage = pilImage.resize((imgWidth,imgHeight), Image.ANTIALIAS)
    image = ImageTk.PhotoImage(pilImage)
    imagesprite = canvas.create_image(w/2,h/2,image=image)
    root.mainloop()

用法

pilImage = Image.open("colagem3.png")
showPIL(pilImage)

输出

它创建一个全屏窗口,您的图像集中在黑色画布上。如果需要,您的图像将被调整大小。这是它的图像:

enter image description here

注意:使用escape关闭全屏

相关问题 更多 >

    热门问题