首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Tkinter破坏Toplevel

Tkinter破坏Toplevel
EN

Stack Overflow用户
提问于 2013-08-22 23:48:54
回答 1查看 951关注 0票数 0

我不能销毁Toplevel (Tkinter,python)

在我的程序中

1)在开始时,用户按下按钮,出现顶层

2)在顶层中有一些更多的小部件和一个按钮

3)当用户按下这个(第二)按钮时,函数(name_of_toplevel.destroy())开始工作

4)但随后终端向我写入"NameError:全局名称'name_of_toplevel‘未定义“

5)但它真的是被定义的!

6)通过bind方法将按钮与函数绑定

程序文本:

代码语言:javascript
复制
from Tkinter import *


def Begin(event):
    okno.destroy()

def QuitAll(event):
    exit(0)

def OpenOkno(event):
    #print "<ButtonRelease-1> really works! Horray!"
    okno = Toplevel()
    okno.title('Question')
    okno.geometry('700x300')

    Sign = Label(okno,text = 'Quit the program?', font = 'Arial 17')
    Sign.grid(row = 2, column = 3)

    OK = Button(okno, text = 'YES',  bg = 'yellow', fg = 'blue', font = 'Arial 17')
    OK.grid(row = 4, column = 2)

    OK.bind("<ButtonRelease-1>",QuitAll)


    NO = Button(okno, text = 'NO', bg = 'yellow', fg = 'blue', font = 'Arial 17')
    NO.grid(row = 4, column = 4)

    NO.bind("<ButtonRelease-1>",Begin)




root  = Tk()  # main window 'program_on_Python'

root.title('Program_on_Python')

root.geometry('400x600')



knpk = Button(root, text = 'click here!', width = 30, height = 5, bg = 'yellow', fg =   'blue', font = 'Arial 17')
knpk.grid(row = 2, column = 2)

knpk.bind("<ButtonRelease-1>",OpenOkno)

root.mainloop()

请帮帮我,如果可以的话

EN

回答 1

Stack Overflow用户

发布于 2013-08-22 23:56:02

okno不存在于OpenOkno函数之外,因此尝试在其他任何地方访问它都会导致NameError。解决这个问题的一种方法是在OpenOkno中移动Begin,其中okno对象是可见的。

代码语言:javascript
复制
def OpenOkno(event):
    def Begin(event):
        okno.destroy()

    #print "<ButtonRelease-1> really works! Horray!"
    okno = Toplevel()
    #etc... Put rest of function here

您还可以使用lambda表达式代替完整的函数,作为Bind的参数。

代码语言:javascript
复制
NO.bind("<ButtonRelease-1>", lambda event: okno.destroy())

您还可以将okno设置为全局变量,这样它将在任何地方都可见。然后,您需要在需要赋值给okno的任何地方使用global okno语句。

代码语言:javascript
复制
okno = None

def QuitAll(event):
    exit(0)

def Begin(event):
    okno.destroy()

def OpenOkno(event):

    #print "<ButtonRelease-1> really works! Horray!"
    global okno
    #etc... Put rest of function here
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18385257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档