Version 5 of toggle button

Updated 2011-02-11 18:12:53 by Jorge

Although standard Tk doesn't supply a toggle button, and most developers seem content to use a checkbox in its place, Uwe Klein illustrates how easy it is to customize a button by refinement of a label:

    set ::state OFF
    label .lb -textvariable ::state -relief raised -bd 4
    bind .lb <ButtonPress-1> {
        if {"$::state" == "OFF"} {
            set ::state ON
            %W configure -relief sunken
        } else {
            set ::state OFF
            %W configure -relief raised
        }
    }
    label .l -textvariable ::state
    pack .lb .l -side left

[Comments: all buttons thus; deserves abstraction; backward-compatible only to 8.?]


KPV: tile has something similar--the Toolbutton style for a checkbutton. This is designed for a button bar, so it usually looks better if you have an image in the widget.

 package require tile
 ::ttk::checkbutton .c1 -text "ON" -style Toolbutton
 pack .c1

MG The Tk checkbutton has very simple support for this feature, too, with the -indicatoron option, which makes it work exactly as a togglebutton.

  pack [checkbutton .c -text "Click me" -indicatoron false]

JM 11Feb2011 radiobutton has this option too, so we can have a mutually exclusive set of buttons:

 pack [radiobutton .o1 -text A -indicatoron false -variable valor -value A]
 pack [radiobutton .o2 -text B -indicatoron false -variable valor -value B]
 pack [radiobutton .o3 -text C -indicatoron false -variable valor -value C]

Category Widget