pack_forget破坏图像有问题 - tkinter

时间:2014-03-30 17:27:34

标签: python tkinter python-3.3

在我的程序中,我遇到了一个错误,我不知道是什么导致它。

一段代码:

sunPic = r'sun.gif'
mercPic = r'merc.gif'


buttonFrame = Frame(root)
buttonFrame.pack(side=LEFT)

textFrame = Frame(root)
textFrame.pack(side=TOP)


def sunInfo():
    textFrame.destroy()
    sunImage = PhotoImage(file=sunPic)
    img1 = Label(textFrame, image = sunImage)
    img1.pack()
    img1.image = sunImage

def mercInfo():
    textFrame.destroy()
    mercImage = PhotoImage(file=mercPic)
    img2 = Label(textFrame, image = mercImage).pack()
    img2.image = mercImage



sun = Button(buttonFrame, text="THE SUN",command=sunInfo)
sun.pack(side=TOP)

mercury = Button(buttonFrame, text="MERCURY",command=mercInfo)
mercury.pack(side=TOP)

使用该代码,当我点击THE SUN或MERCURY按钮时出现此错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
    return self.func(*args)
  File "C:\Users\Ryan\Desktop\python\Projects for Parliament\universe\infoUniverse.py", line 30, in sunInfo
    img1 = Label(textFrame, image = sunImage)
  File "C:\Python33\lib\tkinter\__init__.py", line 2596, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)
  File "C:\Python33\lib\tkinter\__init__.py", line 2075, in __init__
    (widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: bad window path name ".45448776"

有什么问题/导致此错误的原因是什么?

修改

我已更改它,所以功能如下:

def sunInfo():
    textFrame.pack_forget()
    sunImage = PhotoImage(file=sunPic)
    img1 = Label(textFrame, image = sunImage)
    img1.image = sunImage
    img1.pack()


def mercInfo():
    textFrame.pack_forget()
    mercImage = PhotoImage(file=mercPic)
    img2 = Label(textFrame, image = mercImage)
    img2.image = mercImage
    img2.pack()

但是,每当我运行程序并按下按钮时,图像就不会出现。

1 个答案:

答案 0 :(得分:0)

导致错误的行之前的两行,您将销毁textFrame。然后,您尝试使用textFrame作为img1的父级。一旦被销毁,您就无法使用它。