TUTORIAL · Tkinter
Tkinter Tutorial - Scrollbar
This tutorial introduces scrollbar in Python Tkinter.
The Tkinter Scrollbar widget is normally used to scroll widgets like ListBox, Text or Canvas vertically, or Entry horizontally. It shows a slider in the right position.
Tkinter ScrollBar
import tkinter as tk
class Scrollbar_Example:
def __init__(self):
self.window = tk.Tk()
self.scrollbar = tk.Scrollbar(self.window)
self.scrollbar.pack(side="right", fill="y")
self.listbox = tk.Listbox(self.window, yscrollcommand=self.scrollbar.set)
for i in range(100):
self.listbox.insert("end", str(i))
self.listbox.pack(side="left", fill="both")
self.scrollbar.config(command=self.listbox.yview)
self.window.mainloop()
if __name__ == "__main__":
app = Scrollbar_Example()
self.scrollbar = tk.Scrollbar(self.window)
It initiates the Scrollbar instance.
self.listbox = tk.Listbox(self.window, yscrollcommand=self.scrollbar.set)
self.scrollbar.config(command=self.listbox.yview)
We need configure both Listbox and Scrollbar to connect them together correctly.
- Set
yscrollcommandcallback tosetofScrollbar.yscrollcommandis scrollable widgets’ option that is controlled by a scrollbar, and is used to communicted with vertical scrollbars. - Set
commandof theScrollbarto theyviewof theListbox. When the user moves the slider ofScrollbar, it calls theyviewmethod with the proper argument.
Tkinter Horizontal Scrollbar
The horizontal scroll bar is used to scroll the widgets like Text and Entry in the horizontal orientation.
import tkinter as tk
class Scrollbar_Example:
def __init__(self):
self.window = tk.Tk()
self.scrollbar = tk.Scrollbar(self.window, orient=tk.HORIZONTAL)
self.scrollbar.pack(side="bottom", fill="x")
self.text = tk.Text(self.window, wrap="none", xscrollcommand=self.scrollbar.set)
self.text.insert("end", str(dir(tk.Scrollbar)))
self.text.pack(side="top", fill="x")
self.scrollbar.config(command=self.text.xview)
self.window.mainloop()
if __name__ == "__main__":
app = Scrollbar_Example()
self.scrollbar = tk.Scrollbar(self.window, orient=tk.HORIZONTAL)
It initiates a horizontal scroll bar by specifying the orient to be HORIZONTAL.
self.text = tk.Text(self.window, wrap="none", xscrollcommand=self.scrollbar.set)
To scroll the text horizontally, we need to set xscrollcommand to the set method of the Scrollbar, but not yscrollcommand as in the above example.
self.scrollbar.config(command=self.text.xview)
Correspondingly, the callback of the horizontal scroll bar should be connected with the xview method but not yview.