How to add a scrollbar to a window with tkinter?

by raphael_tillman , in category: Third Party Scripts , 11 days ago

How to add a scrollbar to a window with tkinter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 10 days ago

@raphael_tillman 

To add a scrollbar to a window in tkinter, you can use the Scrollbar widget. Here is a simple example of how to add a vertical scrollbar to a window:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import tkinter as tk

root = tk.Tk()

# Create a scrollbar
scrollbar = tk.Scrollbar(root)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

# Create a listbox to demonstrate scrolling
listbox = tk.Listbox(root, yscrollcommand=scrollbar.set)
for i in range(100):
    listbox.insert(tk.END, f"Item {i}")
listbox.pack(side=tk.LEFT, fill=tk.BOTH)

scrollbar.config(command=listbox.yview)

root.mainloop()


In this example, a vertical scrollbar is created and placed on the right side of the window using the Scrollbar widget. The yscrollcommand parameter of the Listbox widget is set to the set method of the scrollbar. Finally, the config method of the scrollbar is called with the yview method of the listbox to set up the scrolling behavior.