Subclassing Tkinter Buttons

B

Bob Greschke

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.

Thanks!

Bob


System = platform[:3].lower()
..
..
class BButton(Button):
if System == "win":
Make a button with " " before and after text
else:
Make a button using the passed text as is
..
..
BButton(Sub, text = "Hello", bg = "blue", fg = "yellow").pack(side = TOP)
BButton(Sub, bg = "yellow", bg = "blue", text = "World").pack(side = TOP)


On "lin", "sun", "dar":
[Hello]
[World]

On "win":
[ Hello ]
[ World ]
 
R

Rob Wolfe

Bob said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top