im new to programming in python but i made a simple GUI using Tkinter that has two Buttons, Start and Quit. When i press the Start button, the GUI freezes and i cant press the Quit button anymore … how can i fix that ?
from tkinter import * from tkinter import ttk import pyautogui import keyboard import time def running(): while keyboard.is_pressed('q') == False: if pyautogui.locateOnScreen('image.png', confidence = 0.9) != None: print("I can see it") time.sleep(1) else: print("I am unable to see it") time.sleep(1) def help(): filewin = Toplevel(root, padx=50,pady=50) information = Label(filewin, text="App made by ..... you can close the app after starting it by pressing the key Q") information.pack() root = Tk() root.title("Rename me later") menubar = Menu(root) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Help", command=help) filemenu.add_separator() menubar.add_cascade(label="Info", menu=filemenu) frm = ttk.Frame(root, padding=30) frm.pack() ttk.Label(frm, text="App made by uknown").grid(column=1, row=0) frm2=ttk.Label(frm, text="").grid(column=0, row=1) frm2=ttk.Label(frm, text="").grid(column=1, row=1) frm2=ttk.Label(frm, text="").grid(column=2, row=1) frm2=ttk.Label(frm, text="").grid(column=0, row=2) frm2=ttk.Label(frm, text="").grid(column=1, row=2) frm2=ttk.Label(frm, text="").grid(column=2, row=2) frm2=ttk.Button(frm, text="Start", command=running).grid(column=0, row=3) frm2=ttk.Label(frm, text="").grid(column=1, row=3) frm2=ttk.Button(frm, text="Quit", command=root.destroy).grid(column=2, row=3) root.config(menu=menubar) root.mainloop()
Advertisement
Answer
You could try running your running
function in its own thread so it doesn’t block the main thread
from threading import Thread def running(): ... # yadda yadda def run_thread() # tell this thread to call the 'running' function th_runner = Thread(target=running, daemon=True) th_runner.start() # start the thread
Then modify your button to call the run_thread()
function instead
frm2=ttk.Button(frm, text="Start", command=run_thread).grid(column=0, row=3)