【发布时间】:2022-01-01 15:40:36
【问题描述】:
起初我在我的一个 tkinter 按钮中使用了 lambda,以便在运行代码时不自行执行函数
Button = tk.Button(root, text="Press me!", width=10, height=2, bg=BuyColor, command=lambda: sample(1, 2))
它运行良好,但后来我不得不面对这个问题,即我的 Tkinter 界面在尝试执行它正在调用的函数时冻结/滞后。
这样,我发现了线程的使用使得 root.mainloop() 在函数运行时不会冻结。
Button = tk.Button(root, text="Press me!", width=10, height=2, bg=BuyColor, command=threading.Thread(target=sample(1, 2)).start())
现在它可以工作了,该函数不会导致 mainloop() 冻结。但是,我现在又遇到了第一个问题。无需点击按钮即可运行功能!
我已经尝试过了,但它仍然会导致程序冻结,即使它有线程。
Button = tk.Button(root, text="Press me!", width=10, height=2, bg=BuyColor, command=lambda: threading.Thread(target=sample(1, 2)).start())
似乎唯一的方法是删除 target=sample() 中的 (),但每次按下按钮时,我都需要使用这些特定变量调用 sample(1, 2) 函数.还有其他按钮调用 sample() 函数,但变量不同。
有没有更有效的方法来做到这一点,而不必为不同的按钮编写不同的功能?
【问题讨论】:
-
应该是
threading.Thread(target=sample, args=(1, 2)).start()。 -
详细说明@acw1668 的回答。当您写
target=sample(1, 2)时,您正在调用sample(1, 2),而不是在按下按钮时。您希望在线程内使用参数1和2调用函数sample。 -
别在意我的最后一条评论,我删除它是因为我修复了它。现在我尝试了
threading.Thread(target=sample, args=(1, 2)).start(),但即使没有按下按钮,它仍然会自行运行 -
哦等等,我认为
lambda:也应该被删除。现在一切正常!我非常感谢您的帮助和详细说明,我现在明白出了什么问题。 -
@acw1668 可以发布答案或投票关闭此问题,因为拼写错误或 OP 也可以删除此问题。
标签: python multithreading tkinter lambda