Skip to content

Instantly share code, notes, and snippets.

@MattWoodhead
Last active June 25, 2017 09:42
Show Gist options
  • Save MattWoodhead/82796750990e4b7741afeeb2c0dff491 to your computer and use it in GitHub Desktop.
Save MattWoodhead/82796750990e4b7741afeeb2c0dff491 to your computer and use it in GitHub Desktop.
An improvement on a common tkinter 'Checkbar', allowing the setting of values after instancing.
"""
An improvement on the tkinter Checkbar example,
available from http://www.python-course.eu/tkinter_checkboxes.php
Author: Matt Woodhead
"""
import tkinter as tk
from tkinter import ttk
class Checkbar(ttk.Frame):
"""
Creates the checkbar class, which defines a set of checkboxes using a list.
Can both return and set the states of individual checkboxes
"""
def __init__(self, parent=None, picks=[], side=tk.LEFT, anchor=tk.W):
ttk.Frame.__init__(self, parent)
self.vars = {}
for pick in picks:
var = tk.IntVar()
chk = ttk.Checkbutton(self, text=pick, variable=var)
chk.pack(side=side, anchor=anchor, expand=1)
chk.invoke()
self.vars[pick] = var # Add the pick to the dictionary
def getvar(self):
""" returns the checkbox values """
return [var.get() for picks, var in self.vars.items()]
def setvar(self, pick, value):
""" sets the value for a specific checkbox in the checkbar """
if pick in self.vars.keys():
self.vars[pick].set(value)
else:
print("incorrect checkbox name")
if __name__ == "__main__":
ROOT = tk.Tk()
FRAME = tk.Frame(ROOT)
BAR = Checkbar(FRAME, ["1", "2", "3"])
BAR.pack()
FRAME.pack()
print(BAR.getvar())
BAR.setvar("2", 0)
print(BAR.getvar())
ROOT.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment