Tkinter Text widget with scrollbar in Python

Python Methods and Functions

In this part of our Tkinter tutorial, we'll take a look at the Tkinter text widget.

Although I've used an object-oriented approach in the previous tutorials, since we'll now look at individual widget examples, it would be easier if I used the module directly.

So, here I will use Tkinter directly, without an explicit Application class.



 Tkinter Text Widget Python




Tkinter Text Widget

This is a widget that allows us to easily view text objects in our application ... For example, if you want to display some lines in the GUI, we can easily use the Text widget to achieve our goal.

Let's see how.

To create a text widget, just use the tk.Text (master, width, height) , where master &this is the main object of the GUI application (using tk.TK () ).

Then we can add text using text_widget.insert () ... 

 import tkinter as tk # Create our master object to the Application master = tk.Tk () # Create the text widget for two lines of text text_widget = tk .Text (master, height = 2, width = 40) # Pack it into our tkinter application text_widget.pack () # Insert text into the text widget # tk.END specifies insertion after the last character in our buffer text_widget.insert (tk .END, "First Line - Hello from AskPython Second Line - Hi") # Start the mainloop tk.mainloop () 

Exit



 Tkinter Text widget

Indeed, there are two lines of text in our text widget!




Adding scrollbars into our text widget

While the above output works for smaller text, what if our text is larger than the width?

We can use Tkinter scrollbar and add it to our text widget. Now that we have added a scrollbar, we can display larger texts correctly.

To create a scrollbar object, use tk.Scrollbar () and add it to our application! We can now display longer texts using a scrolling text widget.

 import tkinter as tk # Create our master object to the Application master = tk .Tk () # Create the text widget te xt_widget = tk.Text (master, height = 5, width = 40) # Create a scrollbar scroll_bar = tk.Scrollbar (master) # Pack the scroll bar # Place it to the right side , using tk.RIGHT scroll_bar.pack (side = tk.RIGHT) # Pack it into our tkinter application # Place the text widget to the left side text_widget.pack (side = tk.LEFT) long_text = "" "This is a multiline string. We can write this in multiple lines too! Hello from AskPython. This is the third line. This is the fourth line. Although the length of the text is longer tha n the width, we can use tkinter's scrollbar to solve this problem! "" "# Insert text into the text widget text_widget.insert (tk.END, long_text) # Start the mainloop tk.mainloop () 

Exit

scrollbar Tkinter Scroll 2

You can see the scroll bar on the right, supported by the text widget on the left.







Tutorials