tk.Text – Scroll bars

It’s possible to add horizontal and vertical scroll bars to a Text widget.

First, we need to create a text widget and set its wordwrap option to none.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import tkinter as tk
from tkinter import ttk


root = tk.Tk()

# Give as much space to row 0, column 0, 
# as it needs when resizing.
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)

# Create a text widget which doesn't wordwrap
# We don't want it to wordwrap because we're 
# going to add scrollbars.
text_widget = tk.Text(root, wrap=tk.NONE)

# Create a horizontal scroll bar and set its 
# command to the text widget (xview).
scrollbar_horizontal = ttk.Scrollbar(root,
                                     orient=tk.HORIZONTAL,
                                     command=text_widget.xview)

# Create a vertical scroll bar and set its 
# command to the text widget (yview).
scrollbar_vertical = ttk.Scrollbar(root,
                                   orient=tk.VERTICAL,
                                   command=text_widget.yview)

# Set the vertical/horizontal commands of the text widget 
# to the appropriate scroll bars.
text_widget.configure(xscrollcommand=scrollbar_horizontal.set,
                      yscrollcommand=scrollbar_vertical.set)


# Show the text widget and scrollbars.
text_widget.grid(row=0, column=0, sticky="ewns")
scrollbar_horizontal.grid(row=1, column=0, sticky="ew")
scrollbar_vertical.grid(row=0, column=1, sticky="ns")

root.mainloop()