'Checkbutton with more than two states in Python (checked, unchecked and something between)

I want to make a Checkbutton (tkinter) in Python with more than two states. I have searched the internet but have not found anything. (perhaps I have not searched enough) Can somebody help me -> thanks a lot. :)



Solution 1:[1]

The Checkbutton documentation covers the third state. There is the option tristatevalue which can be used to show the third state (on, off, tristate). There is also the option tristateimage if you are defining custom images for your checkbuttons.

Here's a simple example:

import tkinter as tk

root = tk.Tk()

var1 = tk.StringVar(value="on")
var2 = tk.StringVar(value="off")
var3 = tk.StringVar(value="tristate")
cb1 = tk.Checkbutton(root, text="On", onvalue="on", offvalue="off", tristatevalue="tristate", variable=var1)
cb2 = tk.Checkbutton(root, text="Off", onvalue="on", offvalue="off", tristatevalue="tristate", variable=var2)
cb3 = tk.Checkbutton(root, text="tristate", onvalue="on", offvalue="off", tristatevalue="tristate", variable=var3)

cb1.pack(anchor="w")
cb2.pack(anchor="w")
cb3.pack(anchor="w")

root.mainloop()

screenshot of three states

If you want the user to be able to toggle between the three values, add the following code. Note that this function has hard-coded strings for the three values so you might have to modify it for your own code. Also, I don't know what order you want the values to switch between so in this example the tristate value comes after the "off" value (eg: "on" -> "off" -> "tristate").

def toggle_checkbutton(event):
    checkbutton = event.widget
    varname = checkbutton.cget("variable")
    current_value = checkbutton.getvar(varname)
    if current_value == "on":
        new_value = "off"
    elif current_value == "off":
        new_value = "tristate"
    else:
        new_value = "on"
    checkbutton.setvar(varname, new_value)
    return "break"

cb1.bind("<1>", toggle_checkbutton)
cb2.bind("<1>", toggle_checkbutton)
cb3.bind("<1>", toggle_checkbutton)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1