Search code examples
pythonfunctiontkinter

How to initialize a prewritten function within a function?


I have 2 functions: one that opens a certain window with buttons, and the other one that does stuff that I need and closes a window. It works fine if I defy second function within the first one, but I need them to be separate, and that's the problem.

If I separate them "newWindow" is undefined in "sleep" and therfore program doesn't work.

from re import I
from tkinter import *
from tkinter.ttk import *
from array import *

def sleep(): # only closes a window for now
        newWindow.destroy()

def openNewWindow():
    
    # Toplevel object which will 
    # be treated as a new window
    newWindow = Toplevel()
 
    # sets the title of the
    # Toplevel widget
    newWindow.title("Action")
 
    # sets the geometry of toplevel
    newWindow.geometry("800x400")
        


    for r in range(6):
        btSle = Button(newWindow, text = "Sleep", command = sleep)

        
        btSle.grid(row = r, column = 1, sticky = W, pady = 2)


Solution

  • Have you tried adding a "global NewWindow"?

    from re import I
    from tkinter import *
    from tkinter.ttk import *
    from array import *
    
    def sleep():
        newWindow.destroy()
    def openNewWindow():
        global newWindow # makes the variable visible to each function
        newWindow = Toplevel()
        newWindow.title("Action")
        newWindow.geometry("800x400")
        for r in range(6):
            btSle = Button(newWindow, text = "Sleep", command = sleep)
            btSle.grid(row = r, column = 1, sticky = W, pady = 2)