【问题标题】:Python threading runs all functions at the same timePython 线程同时运行所有函数
【发布时间】:2021-03-03 21:56:53
【问题描述】:

我创建了一个具有 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)

【问题讨论】:

    标签: python multithreading tkinter


    【解决方案1】:

    对于所有这些,而不是写:

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

    尝试:

    threading.Thread(...).start
    

    当按钮被按下时,命令被执行。顺便说一句,如果您为每个按钮命令编写自己的函数会更好。否则,正如@acw1668 建议的那样,如果用户单击按钮两次,您将获得RuntimeError。此外,您可能希望将, daemon=True 放入Thread 构造函数中,以便在主线程停止时线程停止(更多信息here)。

    【讨论】:

    • 您提出的更改将在第二次单击该按钮时引发RuntimeError: threads can only be started once。最好按照您在回答中所说的那样创建新函数来启动线程作业,因为用户可以检查任务是否已经在运行。
    • @acw1668 好点。我会改变我的答案
    猜你喜欢
    • 2012-09-04
    • 2022-06-24
    • 2021-12-16
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    相关资源
    最近更新 更多