简体   繁体   English

使用PIL显示图像而不添加文件格式

[英]displaying an image without adding the file format using PIL

i have written a function that can search through a folder and display a picture in a new window if the file is present but i always have to add the image file format or extension before the function can work. 我编写了一个可以搜索文件夹并在新窗口中显示图片的功能(如果文件存在),但是在该功能正常运行之前,我总是必须添加图像文件格式或扩展名。

is there a way i can work around ignoring the extension like .gif or .png 有没有办法可以解决忽略.gif.png等扩展名的问题

from tkinter import *
from PIL import *

def display_pix():
    hmm   = Toplevel(window)
    hmm.geometry('300x300')
    label = Label(hmm,)
    label.pack()

    PhotoImage(        file = 'C:\\Python34\\' + e.get())
    logo = PhotoImage( file = 'C:\\Python34\\' + e.get()) 
    label.img = logo
    label.config(image = label.img)

 window = Tk()
 e = Entry(  window, width= 20)
 b = Button( window, text = 'search',command = display_pix)
 e.place(x = 50, y = 30)
 b.place(x = 70, y = 50)

 window.mainloop()

If the file is named spam.gif , that's its filename, so you can't open it as just spam . 如果文件名为spam.gif ,那就是其文件名,因此您不能仅将其打开为spam (Yes, Windows Explorer tries to hide this from you, but only to a limited extent—and if you want to do the same thing, you have to do the same thing Windows Explorer does.) (是的,Windows资源管理器会尝试向您隐藏此内容,但仅限于有限的程度,并且,如果您要执行相同的操作,则必须执行Windows资源管理器的相同操作。)

If you want the user to be able to type spam , and for your program to automatically open spam.gif or spam.jpg or spam.png , you need to explicitly look for files matching the pattern you want. 如果希望用户能够输入spam ,并且要让程序自动打开spam.gifspam.jpgspam.png ,则需要明确查找与所需模式匹配的文件。 And you also have to decide what to do if two such files are found, or a file named spam.txt that isn't an image at all, or… 而且,您还必须决定如果找到两个这样的文件,或者根本不是图像的名为spam.txt的文件,该怎么办?

The simplest version (just try to open the first spam.* that you find) is this: 最简单的版本(尝试打开第一个spam.* )是这样的:

def open_image_file(path, name):
    for fullname in os.listdir(path):
        if fnmatch.fnmatch(f, name + '.*'):
            return PhotoImage(file=os.path.join(path, fullname))

Now you can do this: 现在您可以执行以下操作:

logo = open_image_file(r'C:\Python34', e.get())

(If no files named spam.* were found, you'll end up with None . If, say, a text file or an executable was found and PhotoImage raised an exception, you'll get an exception. Otherwise, logo will be a PhotoImage of the first spam.* file.) (如果未找到名为spam.*文件,则最终将显示为None 。如果找到了文本文件或可执行文件,并且PhotoImage引发了异常, PhotoImage引发异常。否则, logo将为第一个spam.*文件的PhotoImage 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM