Python Scrollbar Widget
A scroll bar is a widget that is useful to scroll the text in another widget.For example, the text in the Text, Canvas, Frame or Listbox can be scrolled from top to bottom or left to right using scroll bars.There are two types of scroll bars.They are horizontal and vertical.The horizontal scroll bar is useful to view the text from left to right. The vertical scroll bar is useful to scroll the text from top to bottom.To create a scroll bar, we have to create Scrollbar class object as:
h = Scrollbar(root, orient=HORIZONTAL, bg='green', command=t.xview)
Here, 'h' represents the Scrollbar object which is created as a child to 'root' window.The option 'orient' indicates HORIZONTAL for horizontal scroll bars and VERTICAL indicates vertical scroll bars. 'bg' represents back ground color for the scroll bar.This option may not work in Windows since Window operating system may force some default back ground color for the scroll bar which will not be disturbed by the tkinter. The option 'command' represents the method that is to be executed. The method 'xview' is executed on the object 't'.Here, 't' may represent a widget like Text widget or Listbox.
Similarly, to create a vertical scroll bar 'v', we can write:
v = Scrollbar(root, orient=VERTICAL, bg='green', command=t.yview)
After creating the scroll bar, it should be attached to the widget like Text widget or Listbox as:
t.configure(xscrollcommand=h.set)
Here, 't' indicates Text widget.'xscrollcommand' calls the set() method of horizontal scroll bar.In the same way, we can attach vertical scroll bar as:
t.configure(yscrollcommand=v.set)
Finally, the scroll bar should be attached to the root window using the pack() or grid() methods as:
h.pack(side=BOTTOM, fill=X)
Here, we are attaching the horizontal scroll bar at the bottom of the widget and it spreads across X - axis.Similarly, to attach vertical scroll bar, we can use the following statement:
v.pack(side=RIGHT, fill=Y)
Python Horizontal Scrollbar Example
A Python program to create a horizontal scroll bar and attach it to a Text widget to view the text from left to right.
from tkinter import * class MyScrollbar: def __init__(self, root): self.t = Text(root, width=70, height=15, wrap=NONE) #insert some text into the Text widget for i in range(50): self.t.insert(END, "This is some text") #attach Text widget to root window at the top self.t.pack(side=TOP, fill=X) #create a horizontal scroll bar and attach it to Text widget self.h = Scrollbar(root, orient=HORIZONTAL, command=self.t.xview) #attach Text widget to the horizontal scroll bar self.t.configure(xscrollcommand=self.h.set) #attach Scrollbar to root window at the bottom self.h.pack(side=BOTTOM, fill=X) root = Tk() #create an object to MyScrollbar class ms = MyScrollbar(root) #the root window handles the mouse click event root.mainloop()