Subclassing Tkinter Buttons

Rob Wolfe blue99 at interia.pl
Fri Sep 1 03:55:03 EDT 2006


Bob Greschke wrote:
> I don't use classes much (mainly because I'm stupid), but I'd like to make a
> subclass of the regular Tkinter Button widget that simply adds spaces to the
> passed "text=" when the program is running on Windows (Linux, Solaris, Mac
> add a little space between the button text and the right and left edges of a
> button, Windows does not and it looks bad/can be hard to read).  Below is
> some pseudo code.  What should the guts of the BButton class be?  I can't
> work out how all of the arguments that would be passed to a regular Button
> call get handled.  *args and **kw confuse me and I can't seem to find simple
> enough examples in my mountain of books.

So watch this:

<code>
import Tkinter as Tk
import sys

class MyButton(Tk.Button):
    system = sys.platform[:3]                # 1

    def __init__(self, master=None, **kw):   # 2 3
        if self.system == "win":
            kw["padx"] = kw.get("padx", 0) + 5   # 4
        # alternative solution
        # if "text" in kw and self.system == "win":
        #     kw["text"] = " " + kw["text"] + " "

        Tk.Button.__init__(self, master, **kw)   # 5
</code>

1. system is a class attribute, so is shared by the class and all
    instances of the class
2. __init__ is called immediately after an instance of the class
    is created
3. kw is a dictionary of button options for example:
    {"text": "Hello", "padx": 2}
4. change value of element "padx" or add this element to dictionary kw
5. call parent __init__ method to create button

HTH,
Rob




More information about the Python-list mailing list