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')
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.
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
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
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()
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
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
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()
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")
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
Create the Text widget.
Use the bind() method of the widget to associate an event with a callback function.
Define the callback function to handle the event.
Example: Handling Keyboard Events
import tkinter as tk
# Callback function to handle the eventdef on_key_press(event):
print(f"Key pressed: {event.char}")
# Callback for mouse clickdef 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
Key Press Event (<KeyPress>): Triggered when a key is pressed. The event.char property holds the character of the key pressed.
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.
Exercise on Text
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. )