【问题标题】:how to add image in tkinter?如何在 tkinter 中添加图像?
【发布时间】:2020-08-23 07:13:11
【问题描述】:

我无法将图像(gif 图像)添加到 tkinter 窗口。

from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
root = Tk()
def open_image():
    qr_select = filedialog.askopenfilename(title = "open")
    im = PhotoImage(file=qr_select)
    w1 = Label(window, image = im)
    w1.image = im
    w1.config(image=im)
    w1.pack(side="right")
def window_function():
    global window
    window=Tk()
    window.geometry("800x550+650+250")
    window.title("QR_Scanner")
    btn = Button(window,text = "open a gif picture",command = open_image)
    btn.pack()
    root.iconify()
    window.mainloop()

btn = Button(root,text = "open window",command = window_function)
btn.pack()

root.mainloop()

我的错误是(_tkinter.TclError:图像“pyimage1”不存在)

【问题讨论】:

    标签: python-3.x image tkinter


    【解决方案1】:

    您在窗口中看不到 gif 的原因是您没有对图像进行引用,因此它被 Tkinter 垃圾收集器收集。 Read More About This Here。要添加对图像的引用,您可以这样做:

    w1.image = im
    

    并在此处将其添加到您的代码中:

    def open_image():
        qr_select = filedialog.askopenfilename(title = "open")
        im = PhotoImage(file=qr_select)
        w1 = Label(root, image = im)
        w1.image = im #Keep A Reference To The Image
        w1.config(image=im)
        w1.pack(side="right")
    

    您得到 pyimage1 不存在 的原因是因为您有多个 Tk 实例,并且只有 1 个。您必须通过以下方式将窗口设置为 Toplevel()替换:window=Tk()window=TopLevel()

    【讨论】:

    • 抱歉没注意我去看看
    • 我已经编辑了问题,希望这能解决您的问题!
    • 非常感谢。但是 TopLevel() 是不正确的,我们应该写 Toplevel()。
    • 你是对的,我一定是不小心打错了。
    猜你喜欢
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多