simple button class

Eric Brunel eric.brunel at pragmadev.com
Fri May 30 04:42:11 EDT 2003


Mark Light wrote:
> I am using Tkinter
> 
> 
> "Mark Light" <light at soton.ac.uk> wrote in message
> news:bb5bio$8c8$1 at aspen.sucs.soton.ac.uk...
> 
>>Hi,
>>      I am trying to write a small gui program that has a 24 buttons that
>>are essentially the same. I would like to do this via a class and call an
>>instance for each button. I have read and re-read the class stuff and get
> 
> a
> 
>>bit confused - could some one start me off. Initially I just want a class
>>where each instance would generate a button that when pressed would print
> 
> to
> 
>>stdout I am button 1 I am button 2 .. etc - hopefully I will be able to
> 
> pick
> 
>>things up from there.
>>
>>Many thanks,
>>
>>Mark.

There are many ways to do what you want. Here's one:

---MyButton.py----------------------
from Tkinter import *

class MyButton(Button):

   def __init__(self, parent, buttonNb, **options):
     self.__buttonNb = buttonNb
     apply(Button.__init__, (self, parent), options)
     # Or, if Python version >= 2.2, simply:
     # Button.__init__(self, parent, **options)
     self.configure(command=self.printMyNumber)

   def printMyNumber(self):
     print "Hi! I'm button n#", self.__buttonNb

if __name__ == '__main__':
   root = Tk()
   for i in range(24):
     b = MyButton(root, i, text="Button %s" % i)
     b.pack(side=TOP)
   root.mainloop()
-------------------------------------

Now, just feel free to ask any question about the code above if something is not 
clear to you :-)

HTH
-- 
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com





More information about the Python-list mailing list