Choices between two alternatives are typically implemented with checkboxes and lists of options where each choice is independent from the rest. As we will see in the next example, these concepts can be implemented using the Checkbutton widget.
Implementing switches with checkboxes
How to do it...
The following application shows how to create Checkbutton, which must be connected to an IntVar variable to be able to inspect the button state:
import tkinter as tk class SwitchApp(tk.Tk): def __init__(self): super().__init__() self.var = tk.IntVar() self.cb = tk.Checkbutton(self, text="Active?", variable=self.var, command=self.print_value) self.cb.pack() def print_value(self): print(self.var.get()) if __name__ == "__main__": app = SwitchApp() app.mainloop()
In the preceding code, we simply printed the value of the widget each time it is clicked:
How it works...
Like the Button widget, the Checkbutton also accepts the command and text options.
With the onvalue and offvalue options, we can specify the values used when the button is on and off. We use an integer variable because these values are 1 and 0 by default, respectively; however, you can also set them to any other integer values.
There's more...
With Checkbuttons, it is also possible to use other variable types:
var = tk.StringVar() var.set("OFF") checkbutton_active = tk.Checkbutton(master, text="Active?", variable=self.var, onvalue="ON", offvalue="OFF", command=update_value)
The only restriction is to match onvalue and offvalue with the type of the Tkinter variable; in this case, since "ON" and "OFF" are strings, the variable should be a StringVar. Otherwise, the Tcl interpreter will raise an error when trying to set the corresponding value of a different type.
See also
- The Tracing text changes recipe
- The Creating selections with radio buttons recipe