1

This is my code. All it does is open a window and have a blue button with the word "ice" on it. Once you click the "ice" button, it opens a second window and is supposed to close the second window. But I cant seem to get that to work.

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

It just gives the error:

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

What do I need to add to get this to work?

2 Answers2

0

top is declared as local variable and you need declare this as global variable:

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()
Héctor M.
  • 2,302
  • 4
  • 17
  • 35
0

You assign top inside the function main which means it doesn't exist outside that function and therefore the function secondary can not find it.

You can change the scope of top with global:

def main():
    global top
    ...

Also; you sholuld take a look at Best way to structure a tkinter application

figbeam
  • 7,001
  • 2
  • 12
  • 18