I'm trying to use Tkinter to start a while loop when pressing the "on" button from an option menu and stop that while loop when pressing the "off" from the option menu. The while loop is infinite but I was hoping I could press "off" and it would exit the program. I've looked up another way to do this using try: and keyboardInterruption but I'm really trying to have it stop using the "off" button. Not sure how to code to make the off button work, any suggestions/solutions ? (I'm new to coding, thanks)
import psutil, os, random, webbrowser, sys
import tkinter import*
import tkinter import tkk
import tkinter
import ttkbootstrap as tk
import keyboard
window=tk.Window()
window.title("Channel App")
window.geometry('400x300')
def Selected(event):
if clicked.get()== 'On':
Start_Channel()
else:
clicked.get() == 'Off'
Stop_Channel()
options = [
'On',
'Off'
]
clicked = StringVar()
clicked.set(options[0])
drop= OptionMenu(window, clicked, *options, command= Selected)
drop.grid(row=3,column=0)
def Stop_Channel():
print("Stop Channel")
sys.exit(0)
def Start_Channel():
while True:
vlc_found = any('vlc.exe' in proc.name() for proc in psutil.process_iter())
print(vlc_found)
if (vlc_found == False):
print("Did not find")
basedir=("C:\\Users\\..")
file = random.choice([x for x in os.listdir(basedir) if os.path.isfile(os.path.join(basedir, x))])
print("Playing file {}...".format(file))
webbrowser.open(os.path.join(basedir, file))
elif(Selected(event)==clicked.get()=="Off"):
Stop_Channel()
window.mainloop()
whileloop, the body of that loop is the only thing your program is doing. Your GUI is completely dead at that point, because there's nothing inside the loop that is handling mouse or keyboard events. So this is simply not a workable approach in a GUI program. The general solution in Tkinter is to do one step of the work in your function, then instead of looping, use.after()to schedule another call to the function in the near future (perhaps 100-500 milliseconds later). Since the function isn't running continuously, it doesn't block event handling.webbrowser.open()by justing terminate the current tkinter application.