简体   繁体   English

无法在Tkinter的顶级容器中包含小部件

[英]Not able to include widgets in a Toplevel container in Tkinter

I have code using Tkinter that opens one window, then (after clicking a button) opens a Toplevel container. 我有使用Tkinter代码,它可以打开一个窗口,然后(单击按钮后)打开一个Toplevel容器。 I'm trying to put an Label widget into this additional window, but keep getting an error saying "can't invoke label command: application has been destroyed." 我试图将Label窗口小部件放到这个附加窗口中,但是不断收到错误消息,说“无法调用label命令:应用程序已被破坏”。

How can I keep my root.Tk() window open to avoid this error? 如何保持我的root.Tk()窗口打开以避免此错误?

Here's what my code looks like: 这是我的代码:

import Tkinter
from Tkinter import *

root = Tk()
root.wm_title("First Window")


NewWin = Button(root, text="Click Me!", command=newwin)
NewWin.pack()


def newwin():
    top = Toplevel()
    top.wm_title("Second Window")

Praise = Label(top, text="Good Work!")
Praise.grid()


root.mainloop()

Up until the label I try to install in the second window, the code works. 直到我尝试在第二个窗口中安装的标签,该代码才起作用。 How can I keep both windows up and running? 如何保持Windows正常运行?

The problem is that local variables are not visible to wider scopes. 问题在于局部变量在更大范围内不可见。 Therefore, the top reference does not exist as far as the rest of the program is concerned. 因此,就程序的其余部分而言, top引用不存在。 The easiest option is to put all of that window's logic into the function that creates it. 最简单的选择是将所有窗口逻辑放入创建它的函数中。

from Tkinter import *

root = Tk()
root.wm_title("First Window")

def new_win():
    top = Toplevel()
    top.wm_title("Second Window")
    praise = Label(top, text="Good Work!")
    praise.grid()

new_win_button = Button(root, text="Click Me!", command=new_win)
new_win_button.pack()

root.mainloop()

You could also go to an OO approach and simply save references to all relevant objects within the application: 您也可以采用OO方法,只需保存对应用程序中所有相关对象的引用:

from Tkinter import *

class App(object):
    def __init__(self, parent):
        self.parent = parent
        parent.wm_title("First Window")
        self.new_win_button = Button(root, text="Click Me!", command=self.new_win)
        self.new_win_button.pack()
        self.populate_button = Button(root, text="Populate", command=self.populate)
        self.populate_button.pack()
    def new_win(self):
        self.top = Toplevel()
        self.top.wm_title("Second Window")
    def populate(self):
        self.praise = Label(self.top, text="Good Work!")
        self.praise.grid()

root = Tk()
app = App(root)
root.mainloop()

I've also cleaned up your variable names so that they don't look like class names (eg MyClass vs. my_label ). 我还清理了变量名,以使它们看起来不像类名(例如MyClass vs. my_label )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM