Text : Multi-line data entry widget


Multi-line Input by Text widget in Tkinter


We will keep one Label along with a text box.


Podcast on Tkinter the Python GUI Development



Tkinter Text style & to read input & display text on click event of button by get() & set() methods


User input for multi-line of text. ( for single line of text use Entry)
t1=tk.Text(parent_window,options)
parent_window : Declared Parent window
options : Various options can be added, list is given below.
import tkinter as tk
my_w = tk.Tk() # Parent window 
my_w.geometry("400x180") # Width height of parent window

l1 = tk.Label(my_w,  text='Address')  # added one Label 
l1.grid(row=1,column=1,padx=5,pady=50) # placed on grid 

t1 = tk.Text(my_w, width=40,bg='yellow' , height=4) # Text
t1.grid(row=1,column=2)  # placed on grid 

my_w.mainloop()
To manage layout read more on grid()

Reading data of a Text widget 🔝

Read data from the text box, starting from the first character to the end.
t1.get("1.0",END)
"1.0" mean Line 1 , first char. Similarly END is the string end including the line break.
To remove the line break at the end, modify it as follows.
t1.get("1.0",'end-1c')
Number of chars including line breaks inside a text widget
For a multi-line text above code will remove line break at the last line only. To calculate the total number of chars the user has entered inside the text widget, we have to count the number of line breaks ( excluding the last one ).
len() : Return the number of elements present in an iterable
count() : Counts the number of matching string present.

Copy text to a Label 🔝

Copy user entered text to a Label
When the "Update" button (b1) is clicked, the my_upd function is called, which reads the content from t1 and updates the second label (l2) with this text, replacing its initial "I will update" message. The GUI layout uses the grid system to position widgets neatly across two rows, making it user-friendly and organized.
import tkinter as tk
from tkinter import BOTH, END, LEFT
my_w = tk.Tk()
my_w.geometry("500x300")  
font1=['Arial',22,'normal']
def my_upd():
    #my_str.set(t1.get("1.0",END))  # read the text box data and update the label
    l2.config(text=t1.get("1.0",'end-2c'))

my_str = tk.StringVar() # textvariable of 2nd Label

l1 = tk.Label(my_w,  text='Name', font=font1) # added one Label 
l1.grid(row=1,column=1,padx=2) 

t1 = tk.Text(my_w,  height=2, width=10,bg='yellow',font=font1)# added one text box
t1.grid(row=1,column=2) 

b1 = tk.Button(my_w, text='Update', width=10,bg='red',command=lambda: my_upd()) # button added
b1.grid(row=1,column=3) 

l2 = tk.Label(my_w,  text='I will update', width=20,bg='lightgreen' ,font=font1) # added one Label 
l2.grid(row=2,column=1,columnspan=3,padx=10,pady=20) 
#my_str.set(" I will update") # default text for Lable l2 
t1.focus()
my_w.mainloop() # to keep the window open 

Total number of chars inside the Text widget 🔝

my_str=t1.get("1.0",'end-1c') # excluding the last line break char.
breaks=my_str.count('\n')  # Number of line breaks ( except last one ) 
char_numbers=len(my_str)-breaks # total chars excluding line breaks

Deleting last char inside Text widget 🔝

t1.delete('end-2c')
Counting and restricting chars in Text widget

insert() : Adding string to text widget 🔝

Adding data to a text box my_str1 is the string variable to insert.
t2.insert(tk.END, my_str1) # adding at the end
Adding a string at the beginning ( pushing the default text )
t2.insert('1.0','Welcome ')# first line first position
t2.insert('1.5','Welcome ')# first line 5th  position
Above codes are important to develop applications.

Note that the widely used option textvariable is not available with Text widget

There are many options we can add to text box, the list is available below.

Now let us add the click event of the button linked to text box. We will enter data in our text box , on click of the button the entered data will be displayed at another Label.
import tkinter as tk
from tkinter import BOTH, END, LEFT
my_w = tk.Tk()
my_w.geometry("500x300")  

def my_upd():
    my_str.set(t1.get("1.0",END))  # read the text box data and update the label

my_str = tk.StringVar()

l1 = tk.Label(my_w,  text='Your Name', width=10 ) # added one Label 
l1.grid(row=1,column=1) 

t1 = tk.Text(my_w,  height=1, width=20,bg='yellow')# added one text box
#t1=Entry(my_w, width=10)
t1.grid(row=1,column=2) 

b1 = tk.Button(my_w, text='Update', width=10,bg='red',command=lambda: my_upd()) # button added
b1.grid(row=1,column=3) 

l2 = tk.Label(my_w,  textvariable=my_str, width=20 ) # added one Label 
l2.grid(row=1,column=4) 
my_str.set(" I will update")

my_w.mainloop()
Let us update one text box by using data from another text box.
import tkinter as tk
from tkinter import BOTH, END, LEFT
my_w = tk.Tk()
my_w.geometry("500x400")  

def my_upd():
    my_str1=t1.get("1.0",END)  # read from one text box t1
    t2.insert(tk.END, my_str1) # Add to another text box t2
    
my_str = tk.StringVar()

l1 = tk.Label(my_w,  text='Your Name', width=10 ) # added one Label 
l1.grid(row=1,column=1) 

t1 = tk.Text(my_w,  height=1, width=20,bg='yellow')# added one text box
#t1=Entry(my_w, width=10)
t1.grid(row=1,column=2) 

b1 = tk.Button(my_w, text='Update', width=10,bg='red',command=lambda: my_upd()) # button added
b1.grid(row=1,column=3) 

t2 = tk.Text(my_w, height=1, width=15, bg='#00f000' ) # added one textbox to read 
t2.grid(row=1,column=4) 

my_w.mainloop()

Delete ( or empty ) text box 🔝

We can clear data from the first text box after updating the second. In above code you can two more lines inside the function.
def my_upd():
    my_str1=t1.get("1.0",END)  # read from one text box t1
    t2.insert(tk.END, my_str1) # Add to another text box t2
    t1.delete('1.0',END)       # Delete from position 0 till end 
    t1.update()                # update the delete

Remove all inputs from all text widgets 🔝

Irrespective of number of Text boxes we used in our application, we can remove all user entered data by using winfo_children() which returns all the widget classes of the Tkinter window. Here is the code
for widget in my_w.winfo_children():
        if isinstance(widget, tk.Text):  # If this is an Entry widget 
            widget.delete(0,'end') # Delete all entries 
How Reset button is used to delete all user enterd data and selections

Focus text box 🔝

To keep the ( blinking ) cursor inside text box
t1.focus() 
Adding Scrollbar to Text widget

Methods 🔝

Delete chars from start position to end position
l2.delete(1.4,1.7) # from 4th till 7th position of line one
l2.delete(1.0,END) # from starting till end

get()

print(l2.get(1.4,1.7)) # print from 4th till 7th position of line one
print(l2.get(1.0,END))  # Print from starting till end 

tag_add(), tag_config() & tag_remove() 🔝

tag_add(), tag_config() & tag_remove()
import tkinter as tk
from tkinter import BOTH, END, LEFT
my_w = tk.Tk()
my_w.geometry("400x300")  
l1 = tk.Label(my_w,text='Your Name', width=10) #added one Label 
l1.grid(row=1,column=1) 

t1 = tk.Text(my_w,width=35,height=4) #text box
t1.grid(row=1,column=2,columnspan=2,pady=30) 

font1=('Times',16,'underline')
t1.insert(tk.END, "Welcome to plus2net")

t1.tag_add("my_hg", "1.2", "1.13") # tag name my_hg is created 
t1.tag_config("my_hg",background="yellow",foreground="red",font=font1)
t1.tag_remove('my_hg','1.5','1.10') # tag is removed from part 

my_w.mainloop()

Using buttons to trigger events using tags 🔝

We can destroy the tag by using tag_delete(). Similarly we can use tag_remove() and tag_config() by using button clicks.
#t1.tag_delete('my_hg')
b1=tk.Button(my_w,text='Remove tag',command=lambda:t1.tag_remove('my_hg','1.0','1.7'))
b1.grid(row=2,column=2,pady=10)

b2=tk.Button(my_w,text='Green tag',command=lambda:t1.tag_config('my_hg',background="green",foreground="red",font=font1))
b2.grid(row=2,column=3,pady=10)
import tkinter as tk
import webbrowser

def open_link(url):
    webbrowser.open(url)

my_w = tk.Tk()
my_w.geometry("400x200") 
text = tk.Text(my_w, height=5, width=30, cursor="hand2")
text.grid(row=1,column=1,padx=20,pady=20)
text.insert(tk.INSERT, "Visit ")
text.insert(tk.INSERT, "Google", 'link')
text.tag_configure('link', foreground='blue', underline=True)
text.tag_bind('link', '<Button-1>', lambda e: open_link("https://www.plus2net.com"))

my_w.mainloop()

Selecting all data from Text box : Cut Copy Paste 🔝

def select_all(): # to select all text inside Text box 
    e1.tag_add("sel", "1.0","end") # all text selected
    e1.tag_config("sel",background="green",foreground="red")
How all text are selected for Cut copy paste in Text widgets

Undo and redo 🔝

Set attribute undo to true
t1=tk.Text(my_w,height=4,bg='yellow',undo=True)
Use Ctrl + z to undo and Ctrl + y for redo

Tkinter text widget adding tags by usign tag_add(), tag_config(),tag_remove() and tag_delete()


Listing all attributes 🔝

for option in t1.config():
    print(option + ' :' ,str(t1[option]))

Details on Attributes of a textbox 🔝

Background color change by configure
bg Background colour of the text box
t1 = tk.Text(my_w,  width=8, height=1, bg='yellow')
We can update the background colour by using configure()

We have two radio buttons , on select of radio buttons we can change the background colour of the text box.

t1.configure(bg=r1_v.get())

Read more on Radio buttons
Full code is here
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("200x200")  

l1 = tk.Label(my_w,  text='Your Name' ) # added one Label 
l1.grid(row=1,column=1) 

t1 = tk.Text(my_w,  width=8, height=1)
t1.grid(row=1,column=2) 
###### Radio buttons #######
def my_upd():
    t1.configure(bg=r1_v.get()) # update the colour 

r1_v = tk.StringVar()  # We used string variable here
r1_v.set('Yellow')     # Can assign value Appear or Failed

r1 = tk.Radiobutton(my_w, text='Yellow', variable=r1_v,
 value='Yellow',command=my_upd)
r1.grid(row=2,column=1) 

r2 = tk.Radiobutton(my_w, text='Red', variable=r1_v,
 value='Red',command=my_upd)
r2.grid(row=2,column=2) 

my_w.mainloop()
bd Border around the Text. Default width is 2
t1 = tk.Text(my_w,  width=8, height=1, bd=6)
cursor cursor that will appear once the mouse is over the text box
t1 = tk.Text(my_w,  width=8, height=1,cursor='circle')
You can get a list of cursor shapes in our Tkinter button page
exportselection Selection is to be exported or not. The default is usually for widgets to export selection.
t1 = tk.Text(my_w,  width=20, height=1,
	exportselection=1)
font Managing font size, family, type etc
t1 = tk.Text(my_w,  width=20, height=1,font=18)
font size with family
my_font=('times', 8, 'bold')
t1 = tk.Text(my_w,  width=20, height=1,font=my_font)
Zoom in & Zoom out of Text by using font size
Managing font using Menu bar
Foreground color change by configure
fg Colour used for fg
l1 = tk.Label(my_w,  text='Your Name' ) # added one Label 
l1.grid(row=1,column=1) 

t1 = tk.Text(my_w,  width=10, height=1,fg='red')
t1.grid(row=1,column=2) 

t2 = tk.Text(my_w,  width=10, height=1,fg='green')
t2.grid(row=1,column=3) 
height Height in number of lines
t1 = tk.Text(my_w,  width=10, height=2)
HeighlightBackground  and heightlightcolor


highlightbackground
focus highlight color ( the rectangle around the text box ) when text box is not in focus.

( Note keep highlightthickness = 2 to get a visible output of the rectangle around the text box )



t1 = tk.Text(my_w,  width=10,height=1,highlightbackground='red')
highlightcolor
focus highlight ( the rectangle around the text box ) color when text box is in focus
t1 = tk.Text(my_w,  width=10,height=1,highlightcolor='red')

highlightthickness
The width of the focus heighlight. ( the rectangle around the text box ) Default value is 1.
t1 = tk.Text(my_w,  width=10,height=1,highlightthickness=2)
Insertbackground insertborderwidth insertofftime insertontime insertwidth

insertbackground
Blinking Cursor background colour.


Here we kept insertwidth=15 to make the cursor thick enough to make it visible.


We have changed insertborderwidth=10 to make the 3 D effect visible.
t1 = tk.Text(my_w,width=10,height=1,
insertbackground='red',insertwidth=15)

insertborderwidth
Widht of the border of Cursor to give 3 D Effect.
t1 = tk.Text(my_w,width=10,height=1,
insertborderwidth=8, insertwidth=18)
insertofftime
The off time in milliseconds for the blinking cursor. For 0 value it will not blink.
t1 = tk.Text(my_w,width=10,height=1,
insertofftime=1000,insertontime=1000)
insertontime
The on time in milliseconds for the blinking cursor.
t1 = tk.Text(my_w,width=10,height=1,
insertofftime=1000,insertontime=1000)
insertwidth
Width of the blinking cursor
t1 = tk.Text(my_w,  width=10,height=1,insertwidth=15)
justify Text justification . Values can be LEFT RIGHT or CENTER
Relief with raised sunken flat ridge solid and groove
relief The text box 3 D effect style. It can take these values
raised , sunken ,flat, ridge, solid & groove
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("250x200")  
l1 = tk.Label(my_w,  text='relief' ) # added one Label 
l1.grid(row=1,column=1) 

l1 = tk.Label(my_w,  text='Raised' ) # added one Label 
l1.grid(row=2,column=1) 

t1 = tk.Text(my_w,  width=10,height=1,relief='raised')
t1.grid(row=2,column=2) 

l1 = tk.Label(my_w,  text='sunken' ) # added one Label 
l1.grid(row=3,column=1) 

t1 = tk.Text(my_w,  width=10,height=1,relief='sunken')
t1.grid(row=3,column=2)

l1 = tk.Label(my_w,  text='flat' ) # added one Label 
l1.grid(row=4,column=1) 

t1 = tk.Text(my_w,  width=10,height=1,relief='flat')
t1.grid(row=4,column=2)

l1 = tk.Label(my_w,  text='ridge' ) # added one Label 
l1.grid(row=5,column=1) 
t1 = tk.Text(my_w,  width=10,height=1,relief='ridge')
t1.grid(row=5,column=2)

l1 = tk.Label(my_w,  text='solid' ) # added one Label 
l1.grid(row=6,column=1) 
t1 = tk.Text(my_w,  width=10,height=1,relief='solid')
t1.grid(row=6,column=2)

l1 = tk.Label(my_w,  text='groove' ) # added one Label 
l1.grid(row=7,column=1) 

t1 = tk.Text(my_w,  width=10,height=1,relief='groove')
t1.grid(row=7,column=2)

my_w.mainloop()
selectbackgroundThe background colour of the selected text inside the textbox.
t1 = tk.Text(my_w,  width=10,height=1,
selectbackground='red')
selectborderwidthThe width of the boarder around selected text
selectforegroundThe colour of the font of selected text
t1 = tk.Text(my_w,  width=10,height=1,
selectforeground='yellow')
widthWidth in number of chars
t1 = tk.Text(my_w,  height=1, width=20)
xscrollcommandAdd scroll bar to text box
wrap values can be char, none, word
How to use Checkbutton to wrap text in Entry widget

How to Add Events to Tkinter Text Widget 🔝

The Tkinter Text widget is versatile and allows you to bind events to it, enabling interactive functionality. Here's how you can add events to a Tkinter Text widget:

Steps to Add Events to a Tkinter Text Widget

  1. Create the Text widget.
  2. Use the bind() method of the widget to associate an event with a callback function.
  3. Define the callback function to handle the event.

Example: Handling Keyboard Events

import tkinter as tk

# Callback function to handle the event
def on_key_press(event):
    print(f"Key pressed: {event.char}")

# Callback for mouse click
def on_mouse_click(event):
    print(f"Mouse clicked at position: {event.x}, {event.y}")

# Create the main application window
root = tk.Tk()
root.title("Text Widget Event Example")

# Create a Text widget
text_widget = tk.Text(root, width=40, height=10)
text_widget.pack(pady=10)

# Bind events to the Text widget
text_widget.bind("<KeyPress>", on_key_press)  # Key press event
text_widget.bind("<Button-1>", on_mouse_click)  # Left mouse click event

# Start the Tkinter main loop
root.mainloop()

Explanation of Code

  1. Key Press Event (<KeyPress>): Triggered when a key is pressed. The event.char property holds the character of the key pressed.
  2. Mouse Click Event (<Button-1>): Triggered when the left mouse button is clicked within the widget. The event.x and event.y properties provide the click's coordinates.

Common Events for Text Widget

Here are some commonly used events that you can bind to a Text widget:
  • <KeyPress>: Detect key presses.
  • <KeyRelease>: Detect key releases.
  • <Button-1>: Detect left mouse button clicks.
  • <Button-3>: Detect right mouse button clicks.
  • <Motion>: Detect mouse movement.
  • <Enter>: Triggered when the mouse enters the widget area.
  • <Leave>: Triggered when the mouse leaves the widget area.

Notes

  • The bound callback functions receive an event object as an argument, which provides detailed information about the event.
  • You can bind multiple events to the same Text widget for richer interactivity.
  1. Exercise on Text
  2. Ask user to enter Name, marks ( in three subjects Physics, Chemistry, Math ) and attendance of a student. On Update , the data will be stored in a Dictionary and finally in a CSV file. ( Break it in parts, First display the data using print(), then create Dictionary and then save as CSV file. )
  3. Create one user data entry box in the window and on click of the Save button the text entered in the entry box will be saved into one text file using the filedialog.
    ( Solution ) Save data entered by user in Tkinter window
  4. Save the above user entered data to one PDF file.
    ( Solution ) Save data entered by user in Tkinter window to PDF file
Python Tkinter Entry How to Validate user entered data Counting and restricting chars in Text widget

Questions 🔝


Tool to generate Hashtags from a string
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer