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()
There are two solutions.
You could actually place
breakto exit the while loop,or you could use a condition in thewhileloop.because sys.exit will stop the entire program.From your question I think you need to close the while loop only, not the window. So,1.Break Approach
2.Condition approach:
WARNING
I am only answering the question you asked, but to be honest the approach you are using can make your app completely non responsive, as
jasonharpersaid when you run a while loop beforetkinter.mainloop()it will prevent event triggering and updates(non responsive window,and will surely crash) so the best approach is to make your code usethreading(ref : threading Gfg) module or use.after()(ref : after method) method, else your app is not going to work properly.Its because tkinter was made to work like that.Also you can usesubprocessmodule to open the VLC instead of usingwebbrowsermodule(or that could also cause errors).