【问题标题】:Tkinter photo not changing after file selection文件选择后Tkinter照片没有改变
【发布时间】:2020-09-22 16:51:08
【问题描述】:

我正在尝试实现一个简单的 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() 函数访问和更改它。程序启动时,会显示一个默认的初始图像,稍后将被用户选择的图像替换。

我面临的问题是用户选择图像后,原始照片消失但新选择的图像没有出现。我不明白为什么会这样。请问有什么帮助吗?

【问题讨论】:

  • 使用config() 方法更新您的标签
  • 将您的布局管理器与您的方法分开以调用标签实例,方法是将其设置为如下变量:my_label = tk.Label(....)my_label.pack() file_select 中的下一步,您需要 更新 通过调用实例my_label.configure(image=photo1) 你的图像
  • 如果您对stackoverflow.com/questions/63079633/…表示了兴趣

标签: python image tkinter photo


【解决方案1】:

开始吧,首先像这样更改标签,这样它就不会返回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
    

希望这能解决错误,如果有任何疑问,请告诉我。

干杯

【讨论】:

    猜你喜欢
    • 2021-07-07
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    相关资源
    最近更新 更多