我正在尝试实现一个简单的 python GUI 程序,该程序允许用户选择照片并在窗口中查看它以供引用。
这是我的代码:
from tkinter import *
from tkinter.filedialog import askopenfilename
from PIL import Image, ImageTk
filename = "none"
photo1 = ImageTk.PhotoImage
def fileSelect():
global filename
filename = askopenfilename() #input file
global photo1
imageShow = Image.open(filename)
imageShow = imageShow.resize((300, 350), Image.ANTIALIAS)
photo1 = ImageTk.PhotoImage(imageShow)
window = Tk() #Creating window
window.title("Example") #Title of window
imageFirst = Image.open("first.jpg")
imageFirst = imageFirst.resize((300, 350), Image.ANTIALIAS)
photo1 = ImageTk.PhotoImage(imageFirst)
Label (window, image=photo1, bg="white").pack(pady=30) #Display image
Button(window, text="Select File", font="none 16", width=15, command=fileSelect).pack(pady=15)
window.mainloop()
正如您所见,photo1
被声明为全局,以允许 fileSelect()
函数访问和更改它。程序启动时,显示默认的初始图像,稍后将被用户选择的图像替换。
我面临的问题是,用户选择图像后,原始照片消失,但新选择的图像没有出现。我不明白为什么会发生这种情况。请问有什么帮助吗?
最佳答案
开始吧,首先像这样更改标签,这样它就不会返回 None
。
img_l = Label(window, image=photo1, bg="white")
img_l.pack(pady=30) #Display image
然后,将您的函数更改为:
def fileSelect():
global filename, photo1 #keeping reference
filename = askopenfilename() #input file
imageShow = Image.open(filename).resize((300, 350), Image.ANTIALIAS)
photo1 = ImageTk.PhotoImage(imageShow) #instantiate
img_l.config(image=photo1) #updating the image
config()
方法更新标签的图像,更改 PhotoImage 实例的图像没有帮助。您还可以删除代码顶部的
photo1 = ImageTk.PhotoImage
,因为它没有用。尽管请记住,不选择任何文件,仍然会返回错误。这是一种解决方法:
def fileSelect(): global filename, photo1 try: filename = askopenfilename() #input file imageShow = Image.open(filename).resize((300, 350), Image.ANTIALIAS) photo1 = ImageTk.PhotoImage(imageShow) img_l.config(image=photo1) except AttributeError: pass
希望这能解决该错误,如果有任何疑问,请告诉我。
干杯
关于python - 选择文件后 Tkinter 照片没有变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64014282/