问题描述
我正在尝试实现一个简单的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,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,Image.ANTIALIAS) photo1 = ImageTk.PhotoImage(imageShow) img_l.config(image=photo1) except AttributeError: pass
希望这可以解决错误,如果有任何疑问,请告诉我。
欢呼