Last active
June 25, 2017 09:42
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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