Generally, event processing is as follows:
# Coding = utf-8import tkinterdef handler (): '''event processing function''' print "handler" If _ name __= = '_ main __': root = tkinter. TK () # Use the mediation function handleradapotor to set the command to BTN = tkinter. button (text = U' button ', command = handler) BTN. pack () root. mainloop ()
But what should I do if the handler () function requires parameters? It's very easy to use lambda.
# Coding = utf-8import tkinterdef handler (a, B, c): '''event handler ''' print "handler", A, B, CIF _ name __= = '_ main _': Root = tkinter. TK () # Use the mediation function handleradapotor to set the command to BTN = tkinter. button (text = u'button ', command = lambda: handler (a = 1, B = 2, c = 3) BTN. pack () root. mainloop ()
Lambda is really an artifact ~~
But what should I do if I want to use event like BTN. BIND ("<button-1>", Handler)? I 'd like to write an intermediate adapter function.
# Coding = utf-8import tkinterdef handler (event, a, B, c): '''event handler ''' print eventprint "handler", a, B, cdef handleradaptor (fun, ** kwds): ''' the adapter of the event processing function, which is equivalent to an intermediary. Where did the event come from, this may be the greatness of Python. '''return Lambda event, fun = fun, kwds = kwds: Fun (event, ** kwds) if _ name __= = '_ main _': Root = tkinter. TK () BTN = tkinter. button (text = U' button ') # bind the event to BTN using the mediation function handleradaptor. BIND ("<button-1>", handleradaptor (handler, A = 1, B = 2, c = 3) BTN. pack () root. mainloop ()
If you do not want to use a = 1, B = 2, c = 3 lexicographic parameters, you can modify the ** kwds parameter of handleradaptor () to * ARGs, which is flexible! **, * Indicates that anyone who wants to learn Python should know it!