Python Tkinter Quick Check Box
Python Tkinter Quick Check Box

- A quick and very easy tkinter checkbox popup that will let you filter any passed list.
import tkinter as tk
class CheckBoxPopup(tk.Toplevel):
"""
A Tkinter popup window that displays a list of checkboxes based on provided strings.
The window has a fixed size of 600x800, includes a scrollbar for long lists, and features
OK and CANCEL buttons at the bottom left. Selecting OK returns the list of checked strings;
CANCEL returns None.
"""
def __init__(self, parent, options_list, title="Select Options"):
"""
Initializes the popup window.
:param parent: The parent Tkinter widget.
:param options_list: A list of strings to display as checkboxes.
:param title: The title of the popup window (optional).
"""
super().__init__(parent)
self.title(title)
self.geometry("600x800")
self.resizable(False, False)
# Button frame at the bottom left
button_frame = tk.Frame(self)
button_frame.pack(side="bottom", fill="x", anchor="w", padx=10, pady=10)
self.ok_button = tk.Button(button_frame, text="OK", command=self.ok)
self.ok_button.pack(side="left")
self.cancel_button = tk.Button(button_frame, text="CANCEL", command=self.cancel)
self.cancel_button.pack(side="left", padx=10)
# Canvas for scrollable content
self.canvas = tk.Canvas(self, borderwidth=0)
self.frame = tk.Frame(self.canvas)
self.vsb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
self.canvas.configure(yscrollcommand=self.vsb.set)
self.vsb.pack(side="right", fill="y")
self.canvas.pack(side="left", fill="both", expand=True)
self.canvas.create_window((4, 4), window=self.frame, anchor="nw", tags="frame")
self.frame.bind("<Configure>", self.on_frame_configure)
# Add checkboxes
self.vars = []
for option in options_list:
var = tk.BooleanVar(value=False)
checkbox = tk.Checkbutton(self.frame, text=option, variable=var, anchor="w")
checkbox.pack(fill="x", anchor="w", padx=5, pady=2)
self.vars.append((option, var))
# Make the popup modal
self.transient(parent)
self.grab_set()
self.protocol("WM_DELETE_WINDOW", self.cancel)
self.result = None
self.wait_window(self)
def on_frame_configure(self, event):
"""Adjust the scroll region to encompass the inner frame."""
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def ok(self):
"""Collect selected options and close the window."""
self.result = [option for option, var in self.vars if var.get()]
self.destroy()
def cancel(self):
"""Close the window without selecting options."""
self.result = None
self.destroy()
To utilize this class, instantiate it with a parent widget (e.g., the root window) and the list of strings. The selected items will be accessible via the result
attribute after the popup closes. For example:
root = tk.Tk()
options = ["Option 1", "Option 2", "Option 3"] # Example list
popup = CheckBoxPopup(root, options)
selected = popup.result
print(selected) # Outputs the list of selected strings or None if canceled
root.mainloop()