我用什么方法可以用我的代码关闭Tkin中的一个窗口

2024-10-06 08:33:24 发布

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

这是我的密码。它所做的只是打开一个窗口,上面有一个蓝色的按钮,上面写着“冰”。一旦你点击“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()

它只是给出了一个错误:

return self.func(*args) File "E:\Programing\test\Eise.py", line 21, in secondary top.destroy() NameError: name 'top' is not defined

我需要补充什么才能让它工作?你知道吗


Tags: nameimport密码maintkintertopdefbutton
2条回答

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()

在函数main内赋值top,这意味着它在该函数外不存在,因此函数secondary找不到它。你知道吗

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

def main():
    global top
    ...

另外,你应该看看Best way to structure a tkinter application

相关问题 更多 >