简体   繁体   中英

Python threading runs all functions at the same time

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)

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM