Arguments for button command via Tkinter?

Steve Holden steve at holdenweb.com
Mon Oct 31 10:37:11 EST 2005


dakman at gmail.com wrote:
> And yet the stupidity continues, right after I post this I finnally
> find an answer in a google search, It appears the way I seen it is to
> create a class for each button and have it call the method within that.
> If anyone else has any other ideas please tell.
> 
I'm hoping you have simply mis-stated your correct understanding of the 
problem, and that what you really propose to do is create a button class 
of which each button in your interface is an instance.

Let's suppose you want each button to toggle between two colors, but 
that the colors for each button are different. The thing to do is create 
a button class that subclasses the button class of your GUI package 
(whatever that may be), storing the required color values as instance 
attributes.

In wxPython, for example, I would write something like (warning: untested):

import wx

class myButton(wx.Button):

     def __init__(self, color1, color2, *args, **kw):
         wx.Button.__init__(self, *args, **kw)
         self.c1 = color1
         self.c2 = color2
         self.state = False

     def onClick(self, event):
         if self.state:
             self.SetBackgroundColor(self.c1)
         else:
             self.SetBaclgroundColor(self.c2)
         self.state = not self.state

Then when you create a button with, say,

     but1 = myButton(wx.RED, wx.BLUE, ...)

you can associate a click on that button with a bound instance method, 
which you'd do in wxPython like:

     wx.EVT_BUTTON(parent, but1, but2.onClick)

but similar considerations apply to Tkinter, and you appear to have the 
wit to be able to extend the argument to that toolkit.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list