0

I created a tkinter app which has 4 functions. 2 of these functions are functions to upload files and the other 2 functions are functions to modify those files. I want to use the "threading" library because tkinter keeps freezing up when the modification functions are running.

When I run the code with the changed below, all functions run at the same time.

For ex, I dont even click the "Upload" button and the tkitner app prompts me to upload the file, for both functions. How do I make it to where the functions only run when I click the button?

btni = Button(
        root, text="Upload File",width=16, command=threading.Thread(target =open_inv_file).start(), background="blue4", foreground="white"
)
btni.place(x=185, y=220)


btnm = Button(
    root, text="Run",  width=16,command=threading.Thread(target =main).start(), background="blue4", foreground="white"
)
btnm.pack()
btnm.place(x=185, y=250)


btn = Button(
    root, text="Upload File",width=16, command=threading.Thread(target =open_file).start(), background="blue4", foreground="white"
)

btn.place(x=185, y=105)
btn3 = Button(
    root, text="Run", command=threading.Thread(target =run).start(), width=16, background="blue4", foreground="white"
)

btn3.place(x=185, y=137)
Mhcg233366
  • 75
  • 6

1 Answers1

2

For all of them, instead of writing:

threading.Thread(...).start()

try:

threading.Thread(...).start

When the button is pressed the command is executed. By the way it is much better if you write your own function for each button command. Otherwise as @acw1668 suggested you will get a RuntimeError if the user clicks on the button twice. Also you might want to put , daemon=True in the Thread constructor so that the thread stops when the main thread stops (more info here).

TheLizzard
  • 7,248
  • 2
  • 11
  • 31
  • 1
    Your proposed change will raise `RuntimeError: threads can only be started once` when the button is clicked the second time. It is better to create new function to start the thread job as you said in your answer because user can check whether the task is already running or not. – acw1668 Mar 04 '21 at 04:20
  • @acw1668 good point. I will change my answer – TheLizzard Mar 04 '21 at 08:37