Tkinter callback arguments
__peter__ at web.de
Mon Nov 2 10:26:17 CET 2009
Alf P. Steinbach wrote:
>> for x in range(0,3):
>> Button(......, command=lambda x=x: function(x))
> An alternative reusable alternative is to create a button-with-id class.
> This is my very first Python class so I'm guessing that there are all
> sorts of issues, in particular naming conventions.
Pseudo-private attributes, javaesque getter methods, unidiomatic None-
checks, broken naming conventions (**args), spaces in funny places...
> And the idea of creating a reusable solution for such a small issue may be
Screw pythonic, the signal/noise ratio is awful in any language.
> But just as an example, in Python 3.x,
...for achieving less in more lines?
> import tkinter
> # I guess for Python 2.x do "import Tkinter as tkinter" but haven't
> # tested.
> class IdButton( tkinter.Button ):
> def __init__( self, owner_widget, id = None, command = None, **args
> self, owner_widget, args, command = self.__on_tk_command
> self.__id = id
> self.__specified_command = command
> def __on_tk_command( self ):
> if self.__specified_command != None:
> self.__specified_command( self )
> def on_clicked( self ):
> def id( self ):
> return self.__id
> def id_string( self ):
> return str( self.id() );
> def on_button_click( aButton ):
> print( "Button " + aButton.id_string() + " clicked!" )
> window = tkinter.Tk()
> n_buttons = 3
> for x in range( 1, n_buttons + 1 ):
> window, id = x, text = "Button " + str( x ), command =
> on_button_click ).pack()
I'm not grumpy, I just don't like your code ;) And I don't like the notion
that you are about to spread this style with your book...
More information about the Python-list