Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a ttk.Checkbutton to neither on nor off, tristate

Tags:

python

tkinter

I want to set a ttk.Checkbutton widget to its third state. If I have an 'All' Checkbutton that can set or clear a set of Checkbuttons I want it to show Off if all the check buttons are already off, on if they are all on and the tristate if there is a mix.

I have found a way to do this using the widget's state but is there a way to simply use an attached tk.xxVar? A previous answer referred to a tristatevalue that I haven't found a way to access.

The code below is setup to cycle through the 3 states as the button is pressed. It works by changing the state to 'alternate'.

import tkinter as tk
from tkinter import ttk

root=tk.Tk()
root.geometry("+50+50")

var=tk.IntVar()
var.set(0)
current_state=tk.StringVar()

text=[' Checkbutton: Off ', ' Checkbutton: On ', ' CB to Third State ']
def label_update():
current_state.set(text[var.get()])

cb=ttk.Checkbutton(root, variable=var, text='Test Box', command=label_update)
cb.grid()

seq=[1,2]
def tick():
    """ Sets var (tk.IntVar) to 0, 1, 2 in sequence for each tick """
    try:
        var.set(seq[var.get()])
        if var.get()>1: cb.state(['alternate'])  # alternate on
    except IndexError:
        cb.state(['!alternate'])                 # alternate off
        var.set(0)                               # reset count
    label_update()

ttk.Button(root, text=" Click to cycle through states ", command=tick).grid()
ttk.Label(root, textvariable=current_state).grid()
label_update()

root.title("Checkbutton Issue")

root.mainloop()

Thanks for any suggestions.

Edits to correct typos.

like image 658
Tls Chris Avatar asked Jan 30 '26 23:01

Tls Chris


1 Answers

The tristate option is only available for tkinter checkbuttons, not for ttk checkbuttons.

For ttk checkbuttons you can get the third state by setting it's state to "alternate":

the_checkbutton.state(['alternate'])

I don't know for certain whether or not all ttk themes support this third state.

like image 177
Bryan Oakley Avatar answered Feb 01 '26 11:02

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!