Home > Back-end >  How to put Scrollbar inside a Listbox in Tkinter?
How to put Scrollbar inside a Listbox in Tkinter?

Time:11-07

how can i move the scrollbar inside a listbox? See the photo attached i used a red arrow for explain, here is my code:

from tkinter import *
window = Tk()
window.geometry('500x500')
window.config(bg='#3c3f41')
window.state('zoomed')
frame_listbox = Frame(window,bg='#3c3f41')
frame_listbox.pack(side=LEFT)
listbox = Listbox(frame_listbox,font=('Helvetica',30))
listbox.pack(padx=400)
scrollbar = Scrollbar(window)
scrollbar.pack(side=RIGHT,fill=Y)
scrollbar.config(command=listbox.yview)
listbox.config(yscrollcommand=scrollbar.set)
window.mainloop()

I tried to put a scrollbar inside a Listbox, i expect to understand if it's possible or not enter image description here

CodePudding user response:

It is recommended to put the scrollbar just to the right of the listbox instead of inside it. To achieve it:

  • make the scrollbar child of frame_listbox instead of window
  • move option padx=400 from scrollbar.pack(...) to frame_listbox.pack(...)
  • pack listbox to the LEFT side
from tkinter import *
window = Tk()
window.geometry('500x500')
window.config(bg='#3c3f41')
window.state('zoomed')
frame_listbox = Frame(window,bg='#3c3f41')
frame_listbox.pack(side=LEFT,padx=400) # added padx=400
listbox = Listbox(frame_listbox,font=('Helvetica',30))
listbox.pack(side=LEFT) # removed padx=400 and added side=LEFT
scrollbar = Scrollbar(frame_listbox) # changed parent to frame_listbox
scrollbar.pack(side=RIGHT,fill=Y)
scrollbar.config(command=listbox.yview)
listbox.config(yscrollcommand=scrollbar.set)
window.mainloop()

enter image description here

CodePudding user response:

Does this will Help? By using grid instead place.

import tkinter as tk

root = tk.Tk()
root.title("Listbox Operations")

# create the listbox (note that size is in characters)
listbox1 = tk.Listbox(root, width=50, height=6)
listbox1.grid(row=0, column=0)
 
# create a vertical scrollbar to the right of the listbox
yscroll = tk.Scrollbar(command=listbox1.yview, orient=tk.VERTICAL)
yscroll.grid(row=0, column=1, sticky=tk.N tk.S)
listbox1.configure(yscrollcommand=yscroll.set)
  
for i in range(1, 50):
    listbox1.insert(tk.END, i)
     
 
root.mainloop()

Result:

enter image description here

  • Related