简体   繁体   English

Python 线程同时运行所有功能

[英]Python threading runs all functions at the same time

I created a tkinter app which has 4 functions.我创建了一个具有 4 个功能的 tkinter 应用程序。 2 of these functions are functions to upload files and the other 2 functions are functions to modify those files.其中 2 个函数是上传文件的函数,另外 2 个函数是修改这些文件的函数。 I want to use the "threading" library because tkinter keeps freezing up when the modification functions are running.我想使用“线程”库,因为 tkinter 在修改函数运行时会一直冻结。

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.例如,我什至没有点击“上传”按钮,tkitner 应用程序提示我上传文件,这两个功能。 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.顺便说一句,如果您为每个按钮命令编写自己的 function 会更好。 Otherwise as @acw1668 suggested you will get a RuntimeError if the user clicks on the button twice.否则,如@acw1668 建议的那样,如果用户单击按钮两次,您将收到RuntimeError 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 ).此外,您可能希望将, daemon=True放入Thread构造函数中,以便在主线程停止时线程停止(更多信息here )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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