Adding scrollbars inside the graphical user interface is a way of providing ease of use to the user. In Tkinter, there is a built-in widget called “Scrollbar”, which is inside the “ttk” package. This scrollbar can be inserted inside the text widget or even inside the entire frame according to the requirement of the user.
The scroll bar can be added inside the Tkinter Window, and then it can be attached with other widgets like Text, ListBox, frames, and even Canvas.
What is the Tkinter Scrollbar Widget?
The “Scrollbar” widget can be added easily inside the Tkinter GUI by calling its function “Scrollbar()” and the syntax of the Scrollbar() function is as
In the above syntax:
-
- scrollVar is used to refer to and use the Scrollbar widget
- parentWindow is the Tkinter window on which the scrollbar would be added.
- optionsParams are the parameters that are used to customize the working of the scrollbar.
Some of the important parameters include “orient”, which is used to set the orientation of the scrollbar, and “command”, which is used to attach the scrollbar to a widget.
How to Create a Tkinter Scrollbar Inside Tkinter Window?
Start by importing tkinter and all of its packages using the “*”, which will include the “ttk” package as well, and then set up the tkinter window using the following lines:
tkWindow = Tk()
tkWindow.resizable(False,False)
tkWindow.title("Tkinter Scrollbar")
Once the initial frame has been set up, add the text widget and place it in the grid “(0,0)” using the following lines:
text.grid(row=0,column=0,)
After that, create a scroll bar using the following lines of code:
scroll.grid(row=0,column=1,sticky="ns")
In these two lines:
-
- The scrollbar’s orientation is set vertical
- The command is set to the text’s “y-view”, which is the vertical view of the Text widget
- The scroll bar is added in the “(0,1)”
Lastly, to change the position of the scrollbar according to the text, use the following lines:
tkWindow.mainloop()
The complete code snippet is as:
tkWindow = Tk()
tkWindow.resizable(False,False)
tkWindow.title("Tkinter Scrollbar")
text = Text(tkWindow, height=8)
text.grid(row=0,column=0,)
scroll= Scrollbar(tkWindow, orient="vertical", command=text.yview)
scroll.grid(row=0,column=1,sticky="ns")
text['yscrollcommand'] = scroll.set
tkWindow.mainloop()
The output of this code snippet is as follows:
The output verifies that the scroll bar has been added and attached to the Text Widget inside Tkinter Window.
Conclusion
The Tkinter Scrollbar is a widget that provides a visible slider that can be used to “scroll” through the attached widget’s content. This Tkinter scrollbar is extremely useful, especially when resizing the entire frame or window is not a good choice due to having long-form content. Simply create a scrollbar using the “Scrollbar()” function and attach it to the widget using the “command” attribute.