2

here is a code to define a scrollbar in a listbox with Tkinter :

import tkinter as tk

root = tk.Tk()

scrollbar = tk.Scrollbar(root)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

listbox = tk.Listbox(root)
listbox.pack()

for i in range(50):
  listbox.insert(tk.END, i)

listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=s.set)

root.mainloop()

I want to adapt this code to have a scrollbar with checkbuttons, I know I can't fill a Listbox with Checkbuttons because listbox can only contain text

scrollbar = tk.Scrollbar(self)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
categories = ["aaa","bbb","ccc"]
for i in categories:
    var[i] = tk.IntVar()
    chk = tk.Checkbutton(self, text=i, variable=var[i], width=20)
    #chk.select()
    chk.pack()

scrollbar.config(command=s.set)

How can I make my Checkbuttons "scrollable" ?

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
userHG
  • 567
  • 4
  • 29
  • The general approach to scrolling a list of arbitrary widgets is to add them to a Frame, add that Frame to a Canvas via its `.create_window()` method, then attach scrollbars to the Canvas. You won't be doing anything actually canvas-y with the Canvas, it's just the most generic widget that supports scrolling. – jasonharper Feb 19 '19 at 16:18

1 Answers1

1

The most common option is to put the checkbuttons in a frame and then put the frame in a canvas since the canvas is scrollable. There are several examples of things, including this question: Adding a scrollbar to a group of widgets in Tkinter

In the case where you're dealing with a vertical stack of widgets, one siple solution is to embed the checkbuttons in a text widget, since a text widget supports both embedded widgets and vertical scrolling.

Example:

import tkinter as tk

root = tk.Tk()

scrollbar = tk.Scrollbar(root)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

checklist = tk.Text(root, width=20)
checklist.pack()

vars = []
for i in range(50):
    var = tk.IntVar()
    vars.append(var)
    checkbutton = tk.Checkbutton(checklist, text=i, variable=var)
    checklist.window_create("end", window=checkbutton)
    checklist.insert("end", "\n")

checklist.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=checklist.yview)

# disable the widget so users can't insert text into it
checklist.configure(state="disabled")

root.mainloop()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685