Search code examples
pythontkinterlistboxscrollbarpython-3.6

Scrolling through multiple listboxes using one scrollbar without using a class


I would like to use a single (vertical) scrollbar to scroll through multiple listboxes at the same time (synchronised) in Tkinter.

The problem is that all the solutions out there on Stack Overflow seem to use classes to append a single scrollbar to multiple listboxes. I would like to do the same without using a class if that's possible as I haven't got any experience with classes.

Here's a simplified version of my code:

from tkinter import *
import tkinter as tk


root = Tk()

##This code will only scroll through 1 listbox.
listbox1 = Listbox(root)
listbox1.grid(row=1, column=2)
listbox2 = Listbox(root)
listbox2.grid(row=1, column=3)
scrollbary = Scrollbar(root, command=listbox1.yview, orient=VERTICAL)
scrollbary.grid(row=1, column=1, sticky="ns")

for i in range(100):
    listbox1.insert("end","item %s" % i)
    listbox2.insert("end","item %s" % i)

Solution

  • I adapted the code from http://effbot.org/tkinterbook/listbox.htm so that it works outside a class.

    import tkinter as tk
    
    root = tk.Tk()
    
    def yview(*args):
        """ scroll both listboxes together """
        listbox1.yview(*args)
        listbox2.yview(*args)
    
    listbox1 = tk.Listbox(root)
    listbox1.grid(row=1, column=2)
    listbox2 = tk.Listbox(root)
    listbox2.grid(row=1, column=3)
    scrollbary = tk.Scrollbar(root, command=yview)
    listbox1.config(yscrollcommand=scrollbary.set)
    listbox2.config(yscrollcommand=scrollbary.set)
    scrollbary.grid(row=1, column=1, sticky="ns")
    
    for i in range(100):
        listbox1.insert("end","item %s" % i)
        listbox2.insert("end","item %s" % i)
    
    root.mainloop()
    

    If you also want to scroll them together with the mousewheel, see the answer to this question: Scrolling multiple Tkinter listboxes together. The answer is given with a class, but the bindings and functions can also be done without using a class.