Tkinter Scrollbar in Listbox
In the default environment Listbox does not have a scrollbar, but if there are too many options, some of them will not be displayed, so you can add the Scrollbar control to Listbox.
The Scrollbar control can be applied to Listbox, Text and Canvas controls as well.
The format of using Scrollbar is as follows.
Scrollbar(master, options, ...)
The first argument to the Scrollbar( ) method is the parent object, indicating the window in which this scrollbar will be built. The following are other commonly used options parameters within the Scrollbar( ) method.
(1) activebackground
: the color of the scrollbar and the directional arrow when the cursor passes over the scrollbar.
(2) bg or background
: the color of the scrollbar and the directional arrow when the cursor does not pass through the scrollbar.
(3) borderwidth or bd
: the width of the border, the default is two pixels.
(4) command
: the method triggered when the scrollbar is moved.
(5) cursor
: the shape of the cursor when the mouse cursor is on the scrollbar.
(6) elementborderwidth
: the outer width of the scrollbar and the direction arrow, default is 1.
(7) highlightbackground
: the color of the scrollbar when it doesn’t get focus.
(8) highlightcolor
: the color of the scrollbar when it gets the focus.
(9) highlightthickness
: the thickness of the scrollbar when it gets the focus, default is 1.
(10) jump
: the method of command will be triggered every time the scrollbar is dragged for a short distance, the default is 0, if set to 1, the method of command will be triggered only when the mouse button is released.
(11) orient
: HORIZONTAL/VERTICAL can be set as horizontal/vertical axis respectively.
(12) repeatdelay
: the unit is ms, the default is 300ms, you can set the stagnation time of holding down the scrollbar to move.
(13) takefocus
: normal can use the way to switch the scrollbar to become the focus by pressing Tab, if set to 0 then cancel this setting.
(14) toughcolor
: the color of the scrollbar slot.
(15) width
: the width of the scrollbar, the default is 16.
Example#1
Create vertical scrollbar in Listbox.
from tkinter import *
root = Tk()
root.title("apidemos.com")
scrollbar = Scrollbar(root) # Create Scrollbar
scrollbar.pack(side=RIGHT,fill=Y)
# Create Listbox,yscrollcommand pointing to scrollbar.set method
lb = Listbox(root,yscrollcommand=scrollbar.set) # Create Listbox
for i in range(50):
lb.insert(END,"Line " + str(i))
lb.pack(side=LEFT,fill=BOTH,expand=True)
scrollbar.config(command=lb.yview)
root.mainloop()
Output:
Line 12 is the Listbox options parameter yscrollcommand set to scrollbar.set, said the Listbox and scrollbar do linkage.
Line 17 scrollbar.config( ) method is mainly for the scrollbar object set selective parameter content, this example is to set the command parameter, that is, when moving the scrollbar, will go to the implementation of the specified method, this example is the implementation of the Listbox object lb yview ( ) method.