How to pass arguments to a Button command in Tkinter ?

How to pass arguments to a Button command in Tkinter?

Asked on November 20, 2018 in tkinter.
Add Comment


  • 3 Answer(s)

    Here is the answer:

        The use of lambdas in such a scenario, because imo it’s clearer and simple and also doesn’t force you to write lots of wrapper methods if you don’t have          control over the called method, but that’s certainly a matter of taste.

         you do with a lambda note there’s also some implementation of currying in        the functional module, so you can use that.

          button = Tk.Button(master=frame, text='press', command= lambda:                      action(someNumber))
    

     

    Answered on November 20, 2018.
    Add Comment

    Here the solution:

    It can be done by using the standard library functools

    from functools import partial
    #(...)
    action_with_arg = partial(action, arg)
    button = Tk.Button(master=frame, text='press', command=action_with_arg)
    
    Answered on November 20, 2018.
    Add Comment

    See how it works:

    The Python’s ability to provide default values for function arguments gives us a way out too.

    def fce(x=myX, y=myY):
      myFunction(x,y)
    button = Tk.Button(mainWin, text='press', command=fce)
    

    There are  more buttons you can create a function which returns a function are.

    def fce(myX, myY):
      def wrapper(x=myX, y=myY):
        pass
        pass
        pass
        return x+y
      return wrapper
     
    button1 = Tk.Button(mainWin, text='press 1', command=fce(1,2))
    button2 = Tk.Button(mainWin, text='press 2', command=fce(3,4))
    button3 = Tk.Button(mainWin, text='press 3', command=fce(9,8))
    

     

    Answered on November 20, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.