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" ?

1
  • 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. Commented Feb 19, 2019 at 16:18

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.