Home > front end >  Align the scrollbar to the listbox using place (and not pack)
Align the scrollbar to the listbox using place (and not pack)

Time:04-13

I would like to eliminate any trace of "pack" from the code and use only "place", in order to position the scrollbar near the listbox and stretch it along the entire height of the listbox. Previously it worked, then the code was modified with pack.

Now I want to remove all packs and use only place

enter image description here

import tkinter as tk   
from tkinter import ttk
from tkinter.scrolledtext import ScrolledText 


window = tk.Tk()
window.geometry("800x800")

frame_title = tk.Frame(window)
frame_title.pack(fill='both', expand=True, pady=5, padx=5)

listbox_title = tk.Listbox(frame_title, selectbackground="#960000", selectforeground="white", bg="white", width = 50, height = 20)
listbox_title.place(x=1, y=1)
listbox_title.configure(font=("Arial", 12))

scrollbar_title = tk.Scrollbar(frame_title)
scrollbar_title.place(x=500, y=1)

scrollbar_title['command'] = listbox_title.yview
listbox_title.config(yscrollcommand=scrollbar_title.set)

listbox_title.bind('<Double-Button-1>') 


text_download = ScrolledText(window, bg="white", width = 50, height = 10)
text_download.place(x=1, y=500)
text_download.configure(font=("Arial", 14))


window.mainloop()

CodePudding user response:

You could bind the scroll bar to the listbox or text widget directly then it will dynamically change when you change the size of the parent widget as well.

scroll_bar = tk.Scrollbar(frame_title)
scroll_bar.config(command=listbox_title.yview)
listbox_title.config(yscrollcommand=scroll_bar.set)

## For Verticle Scrollbar ##
scroll_bar.place(in_=listbox_title, relx=1.0, relheight=1.0, bordermode="outside")

## For Horzontal Scrollbar ##
scroll_bar.place(in_=listbox_title, relx=0.0, rely=1.0, relwidth=1.0, bordermode="outside")

You can then place the listbox as normal.

Update code:

import tkinter as tk   
from tkinter import ttk
from tkinter.scrolledtext import ScrolledText 


window = tk.Tk()
window.geometry("800x800")

frame_title = tk.Frame(window)
frame_title.pack(fill='both', expand=True, pady=5, padx=5)

listbox_title = tk.Listbox(frame_title, selectbackground="#960000", selectforeground="white", bg="white", width = 50, height = 20)
listbox_title.place(x=1, y=1)
listbox_title.configure(font=("Arial", 12))

## Vertical Scroll Bar ##
scrollbar_title = tk.Scrollbar(frame_title, command=listbox_title.yview, orient="vertical")
listbox_title.config(yscrollcommand=scrollbar_title.set)
scrollbar_title.place(in_=listbox_title, relx=1.0, relheight=1.0, bordermode="outside")

listbox_title.bind('<Double-Button-1>') 


text_download = ScrolledText(window, bg="white", width = 50, height = 10)
text_download.place(x=1, y=500)
text_download.configure(font=("Arial", 14))


window.mainloop()
  • Related