[Tkinter-discuss] Fwd: Toggle buttons

Mark Summerfield list at qtrac.plus.com
Wed Jul 25 09:03:43 CEST 2012

Hi Jane,

On Tue, 24 Jul 2012 14:50:36 -0400
Jane Griscti <jgriscti at gmail.com> wrote:
> Hi Mark ... there is a width value for ttk.Checkbutton.
> I was able to get it work with the code below.  I just forced a width of
> 11 pixels (tried to use the winfo_reqwidth() of another button to get the
> right size but it returns 76 for some reason ... there must be a way to
> get a decent size??)
>         tkinter.ttk.Style().configure('Toggle.Toolbutton',
> anchor='center') self.toggle4 = tkinter.ttk.Checkbutton(self,
>                 style='Toggle.TButton', text="Off (4)", width=-11,
>                 command=lambda *args: self.toggle_style(self.toggle4, 4))
>         self.toggle4.pack(padx=5, pady=5)
>     def toggle_style(self, button, number):
>         if button.instate(("selected",)):
>             button.config(text="Off ({})".format(number))
>             button.config(style="Toggle.Toolbutton")
>         else:
>             button.config(text="On ({})".format(number))
>             button.config(style="Toggle.TButton")
> Jane

You're right about the width option (I was thinking of ttk.Button).

However, I've found two problems with this approach:
(1) button widths differ per platform (so on Windows 7 I need -11 and on
    Linux -9; and this may vary with DPI or other factors, so setting
    width may not be a good idea)
(2) the text is centered (like the other buttons) when in TButton style;
    but is left aligned in Toolbutton style. And there doesn't seem to
    be a justify option for ttk.Checkbuttons.

So, for now, I'm using the style approach for Linux since it works
perfectly there, and for Windows and Mac OS X I'm adding an image to the
button with one image for selected and one for deselected.


Mark Summerfield, Qtrac Ltd, www.qtrac.eu
    C++, Python, Qt, PyQt - training and consultancy
        "Programming in Go" - ISBN 0321774639

More information about the Tkinter-discuss mailing list