Home > Net >  Two concurrent threads using tkinter and threading
Two concurrent threads using tkinter and threading

Time:01-21

I am trying to have two buttons to perform two independent functions in a Tkinter GUI both of them runnning concurrently. I am unable to understand how do I implement the same. I tried to base this from many tutorials and this is still sequential for some reason. Any and all help is appreciated. Thanks!

from tkinter import *
import threading

window = Tk()
window.geometry("500x200 460 170")
window.resizable(0, 0)
window.configure(bg='#030818')

screen_size = (61366, 78)

def opencv_code():
    print("recorder")
    time.sleep(10)

def knob_tracking():
    print("recorder1")

def start_opencv():
    threading.Thread(target=opencv_code()).start()

def start_knob_tracking():
    threading.Thread(target=knob_tracking()).start()

Label(window, text="Microscope", fg="white",bg="#030818",font=("Helvetica", 23, "bold")).pack()
Button(window, text="Recorder", command=start_opencv, bd=0, bg="gray",fg="white",font=("Helvetica", 15, "bold")).place(x=170,y=60)
Button(window, text="Recorder1", command=start_knob_tracking, bd=0, bg="gray",fg="white",font=("Helvetica", 15, "bold")).place(x=170,y=110)

window.mainloop()```

CodePudding user response:

You need to remove the parentheses from the functions you pass to threading, as what you are doing calls the functions, instead of passing the function handle. So change:

def start_opencv():
    threading.Thread(target=opencv_code()).start()

def start_knob_tracking():
    threading.Thread(target=knob_tracking()).start()

to:

def start_opencv():
    threading.Thread(target=opencv_code).start()

def start_knob_tracking():
    threading.Thread(target=knob_tracking).start()

You can verify that this is working correctly by changing the functions to:

def opencv_code():
    print("recorder")
    time.sleep(10)
    print("recorder again")

def knob_tracking():
    print("recorder1")
    time.sleep(5)
    print("recorder1 again")

And pressing both buttons.

  •  Tags:  
  • Related