【问题标题】:How to overwrite an image in Tkinter如何在 Tkinter 中覆盖图像
【发布时间】:2020-07-29 03:01:27
【问题描述】:

我创建了一个简单的图像打开程序,它通过单击按钮打开从 filedialog 中选择的图像,但无论我选择另一个图像,它都会出现在当前图像下方

我希望下一张选择的图像被旧图像替换。

请帮助我该怎么办

from tkinter import *
from PIL import Image,ImageTk
from tkinter import filedialog

root=Tk()
root.title('Image')

def open():
    global my_img
    root.filename = filedialog.askopenfilename(initialdir='/GUI',title='Select A File',filetypes=(('jpg files','*.jpg'),('png files','*.png'),('all files','*.*')))
    my_img = ImageTk.PhotoImage(Image.open(root.filename))
    my_image_lbl = Label(image=my_img).pack()
    
my_btn = Button(root,text='Open File Manager',command=open).pack()

root.mainloop()

【问题讨论】:

    标签: python python-3.x tkinter python-imaging-library tk


    【解决方案1】:

    您应该在open() 外部创建my_image_lbl 并在函数内部更新其图像:

    from tkinter import *
    from PIL import Image,ImageTk
    from tkinter import filedialog
    
    root=Tk()
    root.title('Image')
    
    def open():
        filename = filedialog.askopenfilename(initialdir='/GUI',title='Select A File',filetypes=(('jpg files','*.jpg'),('png files','*.png'),('all files','*.*')))
        if filename:
            my_image_lbl.image = ImageTk.PhotoImage(file=filename)
            my_image_lbl.config(image=my_image_lbl.image)
        
    Button(root,text='Open File Manager',command=open).pack()
    
    my_image_lbl = Label(root)
    my_image_lbl.pack()
    
    root.mainloop()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-31
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多