Reputation: 1781
Code
import tkinter as tk
from tkinter import *
import threading
def main():
root = tk.Tk()
# Gets the requested values of the height and width.
window_width = root.winfo_reqwidth()
window_height = root.winfo_reqheight()
# Gets both half the screen width/height and window width/height
position_right = int(root.winfo_screenwidth()/2 - window_width/2)
position_down = int(root.winfo_screenheight()/2 - window_height/2)
# Positions the window in the center of the page.
root.geometry(f"+{position_right}+{position_down}")
app = MainWindow(root)
root.mainloop()
class MainWindow:
def __init__(self,master):
self.master = master
self.master.title("Sign off check")
self.master.geometry('800x350')
self.frame = Frame(self.master)
self.frame.pack(fill="both", expand=True)
def refresh_progress():
threading.Timer(5.0, refresh_progress).start()
refresh_progress()
if __name__ == '__main__':
main()
Output
Running via CMD - Simple blank Tkinter window is opened up and function (def refresh_progress():
) is running every 5 seconds.
Problem
My problem is - Soon as I close the Tkinter window (by pressing 'x' top right corner). The CMD window is still running in background.
Question
How can I end the CMD from running in background - as soon as the Tkinter window is closed?
Upvotes: 1
Views: 138
Reputation: 463
Use my full code here
import sys
import tkinter as tk
from tkinter import *
import threading
def on_closing():
# you can add a various command here, for example like messagebox or something
timer.cancel()
root.destroy()
sys.exit()
def main():
global root
root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", on_closing) # when user click "X"
# Gets the requested values of the height and width.
window_width = root.winfo_reqwidth()
window_height = root.winfo_reqheight()
# Gets both half the screen width/height and window width/height
position_right = int(root.winfo_screenwidth()/2 - window_width/2)
position_down = int(root.winfo_screenheight()/2 - window_height/2)
# Positions the window in the center of the page.
root.geometry(f"+{position_right}+{position_down}")
app = MainWindow(root)
root.mainloop()
class MainWindow:
def __init__(self,master):
self.master = master
self.master.title("Sign off check")
self.master.geometry('800x350')
self.frame = Frame(self.master)
self.frame.pack(fill="both", expand=True)
def refresh_progress():
global timer
timer = threading.Timer(5.0, refresh_progress)
timer.start()
refresh_progress()
if __name__ == '__main__':
main()
Solved by adding the protocol "WM_DELETE_WINDOW" to root
Upvotes: 1