Reputation: 1498
i want to point, that i am learning python since short time. The question is going be to beginner one.
I need to add command to menu at top of program, which would call function "color_picker("red").
kolory.add_command(label="Czerwony", command=color_picker('red'))
When i am using that, its somehow wrong, cuz its called once the program started, its not waiting for me to click the menu button. (i am sure of it, as i added "showinfo" to that function, and it shows the message before i do anything)
kolory.add_command(label="Czerwony", command=lambda: color_picker('red'))
That one kinda works, but i don't know what does "lambda" mean here. Is it only way to call functions with arguments under menu options?
Same question goes to binding keyboard shortcuts.
okno.bind("1", color_picker)
- that will call the function but does not have the argument, which should be a color. How can i do that?
So, how to assign functions WITH arguments, to keyboard shortcuts and to menu using add_command?
PS. Was searching trough google, but it seems python does not have so good documentation like c# does for example. Or i am too stupid to find it.
EDIT:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
TypeError: color_picker() takes at most 1 argument (2 given)
Thats the error message, when i try to use "pick_red" in okno.bind
Upvotes: 1
Views: 1321
Reputation: 39578
I'm not sure if I understand the question, but here goes;
The problem is that you are calling the color_picker
function (by adding ()
after the function name).
What you want to do is pass the actual function, not the result of the function call as the command
keyword argument, e.g. add_command(label="Czerwony", command=color_picker)
However, since you want to give it a fixed argument 'red'
, you must use partial from functools
, something like;
from functools import partial
pick_red = partial(color_picker, "red")
kolory.add_command(label="Czerwony", command=pick_red)
EDIT:
Now that your error message shows that you are using Tkinter
, we can see that according to documentation the function that is given to bind()
is always passed an event
parameter, so you need a function that can accept it;
def pick_red_with_event(event):
# We really do nothing with event for now but we always get it...
color_picker("red")
okno.bind("1", pick_red_with_event)
Same thing works for okno.bind
, if you have defined pick_red
as above, just do:
okno.bind("1", pick_red)
Upvotes: 3