Steve S
Steve S

Reputation: 84

How to add scrollbars to this listbox

Python V3.6, Windows 7, beginner 1 month.

I'm trying to work out how to add scrollbars to a listbox, using tkinter.
can anyone tell me what I'm doing wrong please?

I have already tried to implement a similar answer from here:How to attach my scrollbar to my listbox widget but I can't get that to work either.

    #listbox window
    edit_space = Listbox(
    master = top,
    selectmode   = 'single',
    width  = 53,
    height = 10,
    fg="blue")
    edit_space.place(x=10, y=130)
    edit_space.bind('<Double-1>', onselect)

    # add scrollbar to listbox
    #not working
    scrollbar = Scrollbar(edit_space)
    edit_space.config(yscrollcommand=scrollbar.set)
    scrollbar.config(command=edit_space.yview)

Upvotes: 1

Views: 405

Answers (1)

PM 2Ring
PM 2Ring

Reputation: 55469

Your main problem is that you didn't tell Tkinter to display your Scrollbar, using .pack, .grid, or .place. But rather than just putting the ListBox and Scrollbar into the window it's neater to put them both into a Frame, so you can treat them as a unit. Here's a short demo derived from your code. I use the pack layout manager instead of .place, since it's easier to use & more flexible.

import tkinter as tk

top = tk.Tk()
top.title('Listbox demo')

def onselect(event):
    # Display the current selection
    idx = edit_space.curselection()[0]
    print(idx, edit_space.get(idx))

# Make a Frame to hold the Listbox and its Scrollbar
frame = tk.Frame(top)
frame.pack()

# Add the listbox
edit_space = tk.Listbox(top, selectmode='single', width=20, height=10, fg="blue")
edit_space.bind('<Double-1>', onselect)

# Add the Scrollbar
scrollbar = tk.Scrollbar(top)

# Pack the Scrollbar first so that it doesn't disappear 
# when the window width is small
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
edit_space.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

# Connect the Scrollbar to the Listbox
scrollbar.config(command=edit_space.yview)
edit_space.config(yscrollcommand=scrollbar.set)

# Put some data into the Listbox
for i, c in enumerate('abcdefghijklmnopqrstuvwxyz'):
    edit_space.insert(tk.END, '{:2}: {}'.format(i, 3 * c))

top.mainloop()

Upvotes: 2

Related Questions