从另一个“def”关闭顶级小部件时出现问题

2024-04-26 11:27:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个def,如下所示。其中一个创建了一个具有两个按钮选项的顶级小部件。其中一个按钮调用另一个def。在另一个def中,我想使用topLevelName.destroy()关闭topLevel小部件。但是我一直收到一个错误,说topLevelName没有定义

我的代码:

def func1():
    print("We are in func1.")
    topLevelName.destroy()      <---Error occurs here. 

def func2():
    topLevelName = tkinter.Toplevel()
    yesButton= tkinter.Button(topLevelName , text="Yes", command=func1)
    noButton= tkinter.Button(topLevelName , text="No",command=topLevelName.destroy)

错误消息:

NameError: name 'topLevelName' is not defined

有人知道我在这里做错了什么吗


Tags: text定义部件tkinterdef选项错误button
1条回答
网友
1楼 · 发布于 2024-04-26 11:27:05

您的topLevelName是局部变量,这意味着它只能在func2内部访问。如果您想在该范围之外访问它,您应该使其成为全局变量或使用类。使用类构建相对较大的GUI是更好的解决方案,但对于这个解决方案,您可以使用全局

topLevelName = None #create the variable in global scope

def func1():
    print("We are in func1.")
    topLevelName.destroy()

def func2():
    global topLevelName   #which means, the changes will be applied in global scope
    topLevelName = tkinter.Toplevel()
    yesButton= tkinter.Button(topLevelName , text="Yes", command=func1)
    noButton= tkinter.Button(topLevelName , text="No",command=topLevelName.destroy)

相关问题 更多 >