How to pass arguments to a Button command in Tkinter?

前端 未结 18 3109
夕颜
夕颜 2020-11-21 07:42

Suppose I have the following Button made with Tkinter in Python:

import Tkinter as Tk
win = Tk.Toplevel()
frame = Tk.Frame(master=win).grid(row=         


        
18条回答
  •  不要未来只要你来
    2020-11-21 08:07

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

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

    See: http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/extra-args.html

    For more buttons you can create a function which returns a function:

    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))
    

提交回复
热议问题