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 ?
JavaScript
x
51
51
1
from tkinter import *
2
from tkinter import ttk
3
import pyautogui
4
import keyboard
5
import time
6
7
def running():
8
while keyboard.is_pressed('q') == False:
9
if pyautogui.locateOnScreen('image.png', confidence = 0.9) != None:
10
print("I can see it")
11
time.sleep(1)
12
else:
13
print("I am unable to see it")
14
time.sleep(1)
15
16
def help():
17
filewin = Toplevel(root, padx=50,pady=50)
18
information = Label(filewin, text="App made by ..... you can close the app after starting it by pressing the key Q")
19
information.pack()
20
21
root = Tk()
22
root.title("Rename me later")
23
24
menubar = Menu(root)
25
filemenu = Menu(menubar, tearoff=0)
26
filemenu.add_command(label="Help", command=help)
27
filemenu.add_separator()
28
menubar.add_cascade(label="Info", menu=filemenu)
29
30
31
frm = ttk.Frame(root, padding=30)
32
frm.pack()
33
34
35
ttk.Label(frm, text="App made by uknown").grid(column=1, row=0)
36
37
frm2=ttk.Label(frm, text="").grid(column=0, row=1)
38
frm2=ttk.Label(frm, text="").grid(column=1, row=1)
39
frm2=ttk.Label(frm, text="").grid(column=2, row=1)
40
41
frm2=ttk.Label(frm, text="").grid(column=0, row=2)
42
frm2=ttk.Label(frm, text="").grid(column=1, row=2)
43
frm2=ttk.Label(frm, text="").grid(column=2, row=2)
44
45
frm2=ttk.Button(frm, text="Start", command=running).grid(column=0, row=3)
46
frm2=ttk.Label(frm, text="").grid(column=1, row=3)
47
frm2=ttk.Button(frm, text="Quit", command=root.destroy).grid(column=2, row=3)
48
49
root.config(menu=menubar)
50
root.mainloop()
51
Advertisement
Answer
You could try running your running
function in its own thread so it doesn’t block the main thread
JavaScript
1
13
13
1
from threading import Thread
2
3
4
def running():
5
6
# yadda yadda
7
8
9
def run_thread()
10
# tell this thread to call the 'running' function
11
th_runner = Thread(target=running, daemon=True)
12
th_runner.start() # start the thread
13
Then modify your button to call the run_thread()
function instead
JavaScript
1
2
1
frm2=ttk.Button(frm, text="Start", command=run_thread).grid(column=0, row=3)
2