Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create a multiline entry with Tkinter?
When creating GUI applications in Tkinter, you might need an input field that accepts multiple lines of text. Unlike the standard Entry widget which only handles single lines, Tkinter provides the Text widget for multiline input.
Basic Multiline Entry
The Text() constructor creates a widget that supports multiline user input ?
from tkinter import *
# Create the main window
win = Tk()
win.title("Multiline Entry Example")
win.geometry("650x250")
# Create a Text widget for multiline input
text = Text(win, height=10, width=50)
text.pack(padx=10, pady=10)
win.mainloop()
This creates a basic multiline text entry field where users can type multiple lines of text.
Adding Scrollbars
For longer text content, you can add scrollbars to the Text widget ?
from tkinter import *
win = Tk()
win.title("Multiline Entry with Scrollbar")
win.geometry("650x300")
# Create a Frame to hold Text widget and scrollbar
frame = Frame(win)
frame.pack(fill=BOTH, expand=True, padx=10, pady=10)
# Create Text widget
text = Text(frame, height=15, width=60)
# Create scrollbar
scrollbar = Scrollbar(frame)
scrollbar.pack(side=RIGHT, fill=Y)
# Configure Text widget with scrollbar
text.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=text.yview)
text.pack(side=LEFT, fill=BOTH, expand=True)
win.mainloop()
Getting Text Content
You can retrieve the content from a Text widget using the get() method ?
from tkinter import *
def get_text_content():
content = text.get("1.0", END)
print("Text content:", repr(content))
win = Tk()
win.title("Get Text Content")
win.geometry("650x300")
# Create Text widget
text = Text(win, height=10, width=50)
text.pack(padx=10, pady=10)
# Add some default text
text.insert("1.0", "Type your multiline text here...\nLine 2\nLine 3")
# Button to get content
btn = Button(win, text="Get Content", command=get_text_content)
btn.pack(pady=5)
win.mainloop()
Text Widget vs Entry Widget
| Feature | Entry Widget | Text Widget |
|---|---|---|
| Lines | Single line only | Multiple lines |
| Scrollbars | Horizontal only | Both horizontal and vertical |
| Text formatting | Limited | Rich text support |
| Use case | Forms, short input | Long text, comments, code |
Conclusion
Use the Text widget when you need multiline input in Tkinter. Add scrollbars for better user experience with longer content, and use get("1.0", END) to retrieve the text content.
