简体   繁体   English

Lambda 和螺纹 Python Tkinter

[英]Lambda and threading in Python Tkinter

At first I used lambda in one of my tkinter buttons in order to not execute a function by itself when running the code起初我在我的一个 tkinter 按钮中使用了 lambda 以便在运行代码时不执行 function

Button = tk.Button(root, text="Press me!", width=10, height=2, bg=BuyColor, command=lambda: sample(1, 2))

It worked well, but then I had to face this problem that my Tkinter interface freezes/lags while attempting to do the function it is calling.它运行良好,但后来我不得不面对这个问题,即我的 Tkinter 接口在尝试执行它正在调用的 function 时冻结/滞后。

With that, I found out about the use of threading that makes it possible for the root.mainloop() to not freeze while the function is running.有了这个,我发现使用线程可以让 root.mainloop() 在 function 运行时不会冻结。

Button = tk.Button(root, text="Press me!", width=10, height=2, bg=BuyColor, command=threading.Thread(target=sample(1, 2)).start())

Now it works, the function does not cause the mainloop() to freeze.现在它可以工作了,function 不会导致 mainloop() 冻结。 However, I'm now experiencing the first problem I've encountered again.但是,我现在又遇到了第一个问题。 The functions are running without even clicking the buttons!无需单击按钮即可运行这些功能!

I've tried this but it still causes the program to freeze even though it has threading.我已经尝试过了,但即使它有线程,它仍然会导致程序冻结。

Button = tk.Button(root, text="Press me!", width=10, height=2, bg=BuyColor, command=lambda: threading.Thread(target=sample(1, 2)).start())

It seems like the only way to do this is to remove the () in the target=sample(), but I need to call the sample(1, 2) function with these specific variables for each time I press the button.似乎这样做的唯一方法是删除 target=sample() 中的 (),但每次按下按钮时,我都需要使用这些特定变量调用 sample(1, 2) function。 There are other buttons that calls the sample() function but with different variables.还有其他按钮调用 sample() function 但具有不同的变量。

Is there a more efficient way to do this without having to write different functions for different buttons?有没有更有效的方法来做到这一点,而不必为不同的按钮编写不同的功能?

Thanks to @acw1668 and @Frank Yellin in the comments, I was able to fix the code.感谢评论中的@acw1668 和@Frank Yellin,我能够修复代码。

The final code for all of this to work together is:所有这些一起工作的最终代码是:

Button = tk.Button(root, text="Press me!", width=10, height=2, bg=YourColor, command=lambda: threading.Thread(target=sample, args=(1, 2)).start())

if the function only needs one variable, it should be:如果 function 只需要一个变量,它应该是:

Button = tk.Button(root, text="Press me!", width=10, height=2, bg=YourColor, command=lambda: threading.Thread(target=sample, args=(1,)).start())

Without the , the code won't work.没有,代码将无法工作。

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

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