命令在tkinter何时使用lambda和回调 [英] commands in tkinter when to use lambda and callbacks

查看:1455
本文介绍了命令在tkinter何时使用lambda和回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在tkinter项目的命令中使用函数之间的区别感到困惑。说我有 self.mb_BO.add_radiobutton(label =Red,variable = self.BO,value = 2,command = self.red)

add语句如何工作的区别在于:
self.mb_BO.add_radiobutton(label =Red,variable = self.BO,value = 2,command = self .red())

其中func red(self)将颜色更改为红色。
self.mb_BO.add_radiobutton(label =Red,variable = self.BO,value = 2,command = lambda:self.red())

I'm confused as to the difference between using a function in commands of tkinter items. say I have self.mb_BO.add_radiobutton(label= "Red", variable=self.BO, value=2, command=self.red) what is the difference in how the add statement works from this: self.mb_BO.add_radiobutton(label= "Red", variable=self.BO, value=2, command=self.red()) where func red(self) changes the color to red. And self.mb_BO.add_radiobutton(label= "Red", variable=self.BO, value=2, command=lambda: self.red())

基本上我不明白这些命令在做什么,什么时候使用回调或函数引用。我花了几个小时在网上查找一个容易跟踪的摘要没有效果,我仍然只是困惑。

Essentially I don't understand what these commands are doing and when to use the callback or function reference. I've spent hours looking online for an easy to follow summary to no avail and I am still just as confused.

推荐答案

好的方式来看看它是想象的按钮或绑定问你的问题什么命令应该点击按钮时调用?如果你给它像 self.red(),你不告诉它什么命令运行,你实际上是运行命令。相反,你必须给它一个函数的名称(或更准确地说,引用)。

A good way to look at it is to imagine the button or binding asking you the question "what command should I call when the button is clicked?". If you give it something like self.red(), you aren't telling it what command to run, you're actually running the command. Instead, you have to give it the name (or more accurately, a reference) of a function.

我推荐这条经验法则:不要使用lambda。像所有好的经验法则,它只适用于,只要你必须问的问题。一旦你明白为什么你应该避免lambda,它是可以使用它,只要有意义。

I recommend this rule of thumb: never use lambda. Like all good rules of thumb, it only applies for as long as you have to ask the question. Once you understand why you should avoid lambda, it's OK to use it whenever it makes sense.

这篇关于命令在tkinter何时使用lambda和回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆