commands in tkinter when to use lambda and callbac

2019-01-26 02:30发布

问题:

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.

回答1:

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.

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.



回答2:

command=self.red binds the function to that widget. command=self.red() binds the return value of that function to that widget. You don't want your widget trying to call, say, a number or a string - you want it to call a function. If you want the widget to call a function with an argument, then you would use a lambda:

command=lambda x=None: print('hello world')