Calling functions with arguments on “command” and “bind”

前端 未结 1 922
谎友^
谎友^ 2021-01-25 02:06

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 cal

1条回答
  •  深忆病人
    2021-01-25 02:33

    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)
    

    0 讨论(0)
提交回复
热议问题