Scrollbars can be added to appropriate widgets such as the Text widget. The idea is that you set up a scrollbar object and then attach that object to things like Text widgets. Let's see how it's done.
Jump to near the end of your code, to just before these two lines:
textArea.pack()
form.mainloop()
To set up a scrollbar object, add this line before the two above:
scrollV = tk.Scrollbar(form, orient=tk.VERTICAL)
To the right of the variable we've called scrollV, we have tk.Scrollbar. In between the round brackets of Scrollbar, we first have our form object. After a comma, we have orient=tk.VERTICAL. This is used to orient a vertical scrollbar.
Now add this line:
scrollV.config(command=textArea.yview)
Make sure you use the config function and not the configure one. In between the round brackets of config, we have command=textArea.yview. The command is used to refresh your text whenever you scroll. The thing you are refreshing is the yview of the textArea.
You now need to attach your scroll bar to the Text widget. Add this line:
textArea.configure(yscrollcommand=scrollV.set)
The configure function of the textArea is used to attach your scroll bar (make sure you don't use config instead of configure). In between the round brackets of configure, you need the parameter yscrollcommand. This is needed for a vertical scrollbar. After an equals sign, you need the name of your scrollbar then a dot. After the dot, the function set is used to set your scrollbar.
Finally, you need to pack your new scrollbar:
scrollV.pack(side=tk.RIGHT, fill=tk.Y)
The two parameters to use for pack are side and fill. The side is set to tk.RIGHT and the fill is set to tk.Y. This should get you a vertical scrollbar. But your code should look like this:
Run your code and load a text file into your text area. You should see this:
You should now have a working scrollbar on the right of your text area.
Horizontal Scrollbars
The code to get a horizontal scrollbar is almost the same as the one for the vertical scrollbar. Only the parameters and their values change. In the code below, we highlighted in bold the changing parameter or value:
scrollH = tk.Scrollbar(form, orient=tk.HORIZONTAL)
scrollH.config(command=textArea.xview)
textArea.configure(xscrollcommand=scrollH.set)
scrollH.pack(side=tk.BOTTOM, fill=tk.X)
Add a horizontal scrollbar to your code and it should look like this:
In order to see the effects of your horizontal scroll bar, you need to set the wrap parameter of the Text widget to NONE:
textArea = tk.Text(form, height=12, width=80, wrap=tk.NONE)
Run your form again and load a text file. In the image below, we've loaded a different text file to the postcodes one:
As you can see, both the horizontal and vertical scrollbars are showing.
In the next lesson, you'll learn how to read a text file line by line. We'll also do some text parsing on our postcode file.
Read a Text File Line by Line >