Scrollable Frames in Tkinter
A scrollbar is a widget that is useful to scroll the text in another widget. For example, the text in Text, Canvas Frame or Listbox can be scrolled from top to bottom or left to right using scrollbars. There are two types of scrollbars. They are horizontal and vertical. The horizontal scrollbar is useful to view the text from left to right. The vertical scrollbar is useful to scroll the text from top to bottom.
Now let us see how we can create a scrollbar. To create a scrollbar we have to create a scrollbar class object as:
h = Scrollbar(root, orient='horizontal')
Here h represents the scrollbar object which is created as a child to root window. Here orient indicates horizontal for horizontal scrollbar and vertical indicates vertical scroll bars. Similarly to create a vertical scrollbar we can write:
v = Scrollbar(root, orient='vertical')
On attaching the scrollbar to a widget like text box, list box, etc we then have to add a command xview for horizontal scrollbar and yview for the vertical scrollbar.
h.config(command=t.xview) #for horizontal scrollbar
v.config(command=t.yview) #for vertical scrollbar
Now let us look at the code for attaching a vertical and horizontal scrollbar to a Text Widget.
Python3
from tkinter import *
class ScrollBar:
def __init__( self ):
root = Tk()
h = Scrollbar(root, orient = 'horizontal' )
h.pack(side = BOTTOM, fill = X)
v = Scrollbar(root)
v.pack(side = RIGHT, fill = Y)
t = Text(root, width = 15 , height = 15 , wrap = NONE,
xscrollcommand = h. set ,
yscrollcommand = v. set )
for i in range ( 20 ):
t.insert(END, "this is some text\n" )
t.pack(side = TOP, fill = X)
h.config(command = t.xview)
v.config(command = t.yview)
root.mainloop()
s = ScrollBar()
|
Output:
Last Updated :
04 Mar, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...