Python Unwantedly Executes Command on Run Python Unwantedly Executes Command on Run tkinter tkinter

Python Unwantedly Executes Command on Run


I think what is happening is that you are destroying the window in the timer class method. After your for loop, x will equal 0. Therefore it is more than -1, and the window class is destroyed. Quitbutton trys to use window but it has been destroyed.

In the output I assume you are seeing 'Bye'

I got the correct result with the following:

import tkinter as ttkfrom time import sleep##Application main window setup.window = ttk.Tk()window.maxsize(width=200, height=200)window.minsize(width=200, height=200)window.config(bg=("black"))window.title("Hello World")##Set a 'class' for exit function of application.class Exit():    """    Defines the countdown timer and sets parameters     that need to be satisfied before exit.    """    def __init__(self):        self.countdown = 3        swell = ttk.Label(text=("Hello World!"), bg=("black"),                          fg=("white"), font=("Times New Roman", 12, "bold"))        swell.place(x=50,y=50)    def quit(self):        for iteration in reversed(range(0, self.countdown + 1)):            print(iteration)            sleep(1)        print("Bye!")        window.destroy()##Retrieve the defined 'timer' function from the 'Exit' class.exit=Exit()##Button with attahced command to execute the exit of application via user input.quitButton=ttk.Button(    window,text=("Terminate"), bg=("red"), fg=("white"), font=("bold"),    width=20, height=1, anchor=ttk.S, command=lambda: exit.quit())quitButton.place(x=6,y=150)window.mainloop()

You can see here I also used the init method in the exit class. Its a special kind of method which will auto run when the class is initiated.

It didn't require much changing. All I did was move the destroy window function into its own class method and had the second window instance command be set to run this method.