Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Пробовали ли вы добавить "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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading