1

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.

4
  • Can u post more code on self.red() if you have it?.. Commented Jun 11, 2015 at 1:02
  • def red(self): self.window2.configure(background = 'red') Commented Jun 11, 2015 at 1:07
  • this example works fine in my game code but I was just curious why. Commented Jun 11, 2015 at 1:08
  • Alright, I see you got a clear answer down here...:) Commented Jun 11, 2015 at 1:09

2 Answers 2

6

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')
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.