[英]Python threading runs all functions at the same time
我创建了一个具有 4 个功能的 tkinter 应用程序。 其中 2 个函数是上传文件的函数,另外 2 个函数是修改这些文件的函数。 我想使用“线程”库,因为 tkinter 在修改函数运行时会一直冻结。
当我运行以下更改的代码时,所有函数同时运行。
例如,我什至没有点击“上传”按钮,tkitner 应用程序提示我上传文件,这两个功能。 当我单击按钮时,我如何才能使其功能只运行?
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)
对于他们所有人,而不是写:
threading.Thread(...).start()
尝试:
threading.Thread(...).start
当按钮被按下时,命令被执行。 顺便说一句,如果您为每个按钮命令编写自己的 function 会更好。 否则,如@acw1668 建议的那样,如果用户单击按钮两次,您将收到RuntimeError
。 此外,您可能希望将, daemon=True
放入Thread
构造函数中,以便在主线程停止时线程停止(更多信息here )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.