【问题标题】:How to add background as images to multiple windows linked to a single project using label如何将背景作为图像添加到使用标签链接到单个项目的多个窗口
【发布时间】:2019-09-05 03:23:43
【问题描述】:

我想在 Tkinter Python 中为我的窗口添加一个图像作为背景,这些窗口使用按钮相互链接。默认情况下,当我运行代码时,我的第一个窗口会打开图像,并且在按下按钮到另一个窗口时它也会打开,但是当我按下返回按钮到第一个窗口时,它会给我pyimage3 does not exists 错误。

tkinter.TclError: image "pyimage3" doesn't exist

我已经尝试了上面链接上发布的解决方案,但没有一个对我有用。

from tkinter import *


def win1():

    global window1
    global window2

    def goto2():
        window1.withdraw()
        win2()

    window1=Tk()
    window1.title('Window1')
    window1.geometry('300x300')


    img1=PhotoImage(file='wood.png')
    l1=Label(window1,image=img1,width=160,height=300)

    l1.image = img1

    l1.place(x=0,y=0)


    b=Button(window1,text='go to 2',command=goto2)
    b.pack()
    window1.mainloop()


def win2():
    global window2
    global window1

    def goto1():
        window2.withdraw()
        win1()



    window2=Toplevel()
    window2.title('Window2')
    window1.geometry('300x300')

    img2=PhotoImage(file='for.png')
    l2=Label(window2,image=img2,width=160,height=300)
    l2.image = img2

    l2.place(x=0,y=0)


    b1=Button(window2,text='go to  1',command=goto1)
    b1.pack()
    window2.mainloop()


win1()


错误


File "/usr/lib/python3.7/tkinter/__init__.py", line 2299, in __init__
    (widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage3" doesn't exist

【问题讨论】:

  • 除其他外,您切换窗口的方式被破坏了。建议您使用不同的架构,请参阅this answer 了解另一种选择。

标签: python tkinter


【解决方案1】:

最好按照 martineau 的建议使用不同的方法,但您的方法也可以进行两个小改动。

首先,您不必调用window2.mainloop(),因为您使用的是Toplevel

其次,由于您在 window1 上调用了 withdraw - 只需使用 deiconify() 将其召回。

def win2():
    global window2
    global window1

    def goto1():
        window2.destroy()
        #win1()
        window1.deiconify()


    window2=Toplevel()
    window2.title('Window2')
    window1.geometry('300x300')

    img2=PhotoImage(file='clear.png')
    l2=Label(window2,image=img2,width=160,height=300)
    l2.image = img2

    l2.pack()


    b1=Button(window2,text='go to  1',command=goto1)
    b1.pack()
    #window2.mainloop()

【讨论】:

    猜你喜欢
    • 2019-11-15
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2019-05-24
    相关资源
    最近更新 更多