0

I created a GUI with tkinter with different functions containing selenium and beautifulsoup.

from tkinter import *
import threading

def f1():
    #whatever function 1

def f2():
    #whatever function 2

def f3():
    #whatever function 3

def f4():
    #whatever function 4

root = Tk()
root.title("Test")

button1 = Button(root, text = "Test1", command = f1)
button2 = Button(root, text = "Test2", command = f2)
button3 = Button(root, text = "Test3", command = f3)
button4 = Button(root, text = "Test4", command = f4)

button1.grid(row = 1, column = 0)
button2.grid(row = 1, column = 1)
button3.grid(row = 1, column = 2)
button4.grid(row = 1, column = 3)

mainloop()

Whenever I click on any of these buttons, the GUI freezes for a few seconds, because the function is running for this time. Now I try to use multithreading with code like button1 = Button(root, text = "Test1", command = threading.Thread(target = f1).start) . For the first click on this button, it works perfectly fine. But when I click on this button for a second time, I get an error, because the thread is already started/running. How do I fix this?

Phil
  • 65
  • 8
  • Begin with putting your code inside an `if __name__ == "__main__":` https://stackoverflow.com/questions/419163/what-does-if-name-main-do – Mandera Dec 15 '20 at 11:34
  • 1
    Make sure that you use multi threading on all your function calls, otherwise the moment you initiate any of your time consuming functions on the main thread, your entire program will not respond and cease to take any further input until that is completed. – astqx Dec 15 '20 at 11:47
  • 1
    You should use: `command=lambda: threading.Thread(target=f1).start()`. – acw1668 Dec 15 '20 at 11:49

0 Answers0