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
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
. (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.)
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. 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…
The simplest version (just try to open the first spam.*
that you find) is this:
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.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.