Python自定义弹窗与父窗口

-1 投票
1 回答
541 浏览
提问于 2025-04-18 13:13

我正在尝试制作一个自定义的弹出窗口,用来作为我正在开发的程序的关于页面。不过,当我在调用这个弹出窗口之前已经有另一个窗口存在时,我会收到一个tcl的错误信息,提示图像不存在。顺便说一下,我使用的是Python 3.3.4。

以下是我代码的完整摘录:

#!python3

from tkinter import *
import PIL.ImageTk
import os
__version__ = "part number"

class Screen():
    def __init__(self):
        aboutscreen = Tk()
        aboutscreen.title("About")
        aboutscreen.photoimg = PIL.ImageTk.PhotoImage(file="Logo.bmp")
        Label(aboutscreen, image=aboutscreen.photoimg).pack()
        Label(aboutscreen, text = "company name", width = 25, font = ("ariel",16)).pack()
        Label(aboutscreen, text = "program name", width = 30, font = ("ariel",12)).pack()
        Label(aboutscreen, text = "Part Number: " + __version__, width = 30, font = ("ariel",12)).pack()
        Label(aboutscreen, text = "Copyright company name", width = 30, font = ("ariel",12)).pack()
        while 1:
            try: aboutscreen.update() #keep update window updated until destroyed
            except: break #break loop when destroyed


if __name__ == "__main__":
    root = Tk()
    app = Screen()

这段代码就是让我收到错误信息的原因:

    line 15, in __init__
    Label(aboutscreen, image=aboutscreen.photoimg).pack()
  File "C:\Python33\lib\tkinter\__init__.py", line 2607, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)
  File "C:\Python33\lib\tkinter\__init__.py", line 2086, in __init__
    (widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage1" doesn't exist

但是如果我把root = Tk()这一行注释掉,它就能正常工作。

有人能告诉我我哪里出错了吗?

谢谢

詹姆斯

1 个回答

0

如果你这样做的话,应该就能正常工作:

app = Screen(root)

然后把这个去掉:

aboutscreen = Tk()

我觉得问题出在有多个根窗口,或者说多个Tk实例上。

补充说明:

我在一个邮件列表上发现了这个:

“Tkinter.Tk()会创建一个新的Tcl解释器。你确定你想要这样吗?创建额外窗口的标准方法是使用Tkinter.Toplevel()。”

PhotoImage是在默认的(第一个)解释器中创建的,然后在Label的(第二个)解释器中查找。至少这是我从

class Image:
    """Base class for images."""
    _last_id = 0
    def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
        self.name = None
        if not master:
            master = _default_root
            if not master:
                raise RuntimeError, 'Too early to create image'
        self.tk = master.tk

在Tkinter源代码中推断出来的,这也让人觉得通过指定一个明确的主窗口可以避免这个问题

def showPicture(imageFilename):
    root = Tk()
    # ...
    imageObject = PhotoImage(file=imageFilename, master=root)
    # ...

撰写回答