我可以用什么方式使用我的代码来关闭Tkinter中的窗口

时间:2018-05-26 00:18:19

标签: python tkinter

这是我的代码。它只是打开一个窗口,上面有一个蓝色的按钮,上面写着“冰”字样。单击“ice”按钮后,它会打开第二个窗口,并且应该关闭第二个窗口。但我似乎无法让它发挥作用。

from tkinter import *
import tkinter.messagebox
import os.path        

def main():
    #opening first window
    top=Tk()
    #changing window size, color, and name
    top.configure(bg="#AED6F1")
    top.geometry("800x600+300+80")
    top.title()
    #Button to get login screen
    Button_1 =   Button(top,text="Ice",
                        bg="#AED6F1",relief=FLAT,
                        bd=0,font="Times 
                        100 bold",command=secondary)

    Button_1.place(x=0,y=0)
    top.mainloop()
def secondary():
    top.destroy()
main()

它只是给出错误:

  

返回self.func(* args)文件“E:\ Programing \ test \ Eise.py”,第21行,in   secondary top.destroy()NameError:名称'top'未定义

我需要添加什么才能让它发挥作用?

2 个答案:

答案 0 :(得分:0)

top被声明为局部变量,您需要将其声明为全局变量:

from tkinter import *
import tkinter.messagebox
import os.path        

def main():

    #create all windows

    global top, down, left, right # Declare all windows as global

    top = down = left = right = Tk() # All window variables are Tk()

    #changing window size, color, and name
    top.configure(bg="#AED6F1")
    top.geometry("800x600+300+80")
    top.title()
    #Button to get login screen
    Button_1 = Button(top, text="Ice",
                        bg="#AED6F1",relief=FLAT,
                        bd=0,font="Times 100 bold",command=secondary)

    Button_1.place(x=0,y=0)
    top.mainloop()
def secondary():
#destroy all windows
    top.destroy()
    down.destroy()
    left.destroy()
    right.destroy()
main()

答案 1 :(得分:0)

您在函数top中分配main,这意味着它在该函数之外不存在,因此函数secondary找不到它。

您可以使用top更改global的范围:

def main():
    global top
    ...

也;你sholuld看看Best way to structure a tkinter application