lundi 22 juin 2020

Very long checklist box with tkinter

I'm using the code from this answer to make a list with checkboxes.

import tkinter as tk

root = tk.Tk()

class ChecklistBox(tk.Frame):
    def __init__(self, parent, choices, **kwargs):
        tk.Frame.__init__(self, parent, **kwargs)
        
        self.vars = []
        bg = self.cget("background")
        for choice in choices:
            var = tk.StringVar(value=choice)
            self.vars.append(var)
            cb = tk.Checkbutton(self, var=var, text=choice,
                                onvalue=choice, offvalue="",
                                anchor="w", width=20, background=bg,
                                relief="flat", highlightthickness=0
            )
            cb.pack(side="top", fill="x", anchor="w")
    
    
    def getCheckedItems(self):
        values = []
        for var in self.vars:
            value =  var.get()
            if value:
                values.append(value)
        return values

choices = [str(e) for e in range(100)]
checklist = ChecklistBox(root, choices, bd=1, relief="sunken", background="white")
checklist.pack()

Since the list of choices is very long, I would like to add a scrollbar to this list. What is the best way to do this ?


I tried to follow the example here, but ChecklistBox doesn't have a yview method, and has no yscrollcommand option. I don't know how to circumvent this problem.




Aucun commentaire:

Enregistrer un commentaire