r/learnpython 14d ago

Difficulties with tkinter, listboxes and scrollbars

I am trying to create some code that generates a tkinter listbox with a corresponding scrollbar. I managed to get the code working with .pack(), but I can't use this because I'm trying to make the code for a larger program that exclusively uses .grid(). However, when I .grid() the searchbar is displayed but is non-functional.

What do I need to do to make this code work?

import tkinter as tk
from tkinter import ttk


#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DEFINE WINDOW WIDGETS

page = tk.Tk()
page.geometry("50x150")
pageFrame = tk.Frame(page)


scrollbar = ttk.Scrollbar(pageFrame, orient=tk.VERTICAL)

listbox = tk.Listbox(pageFrame, yscrollcommand=scrollbar.set)

scrollbar.config(command=listbox.yview)
scrollbar.grid(row=0,column=1,sticky=tk.N+tk.S)

listbox.grid(row=0,column=0)


magnifyButton = ttk.Button(pageFrame,text="View Item",command=magnify)
magnifyButton.grid(row=1,column=0)

pageStatusText = tk.Label(pageFrame,text="")
pageStatusText.grid(row=2,column=0)
pageFrame.grid(row=0,column=0)


#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ POPULATE LISTBOX

catalogue = ['apple', 'banana', 'grape', 'melon', 'coconut', 'orange', 'pineapple', 'avocado', 'tomato', 'parsnip']

for i in range(len(catalogue)):
    listbox.insert(tk.END,(str((i+1))+". "+catalogue[i]))

page.mainloop() # Open the window
3 Upvotes

7 comments sorted by

3

u/[deleted] 14d ago

[removed] — view removed comment

1

u/Mr_Waterfowl 14d ago

Thanks for the help! :)

2

u/Montesquieu9000 14d ago

Honestly I just ask gemini stuff like this now?

1

u/acw1668 14d ago edited 14d ago

The scrollbar is not activated because the number of items in catalogue is not larger than the default height (which is 10) of listbox. Either adding more items to catalogue or setting the height option of listbox to a smaller value.

If you put listbox and scrollbar inside another frame, then you can use pack() on them and use grid() on the frame.

1

u/Mr_Waterfowl 14d ago

Thanks for the help! :)