Of course! "Python text tkinter" is a great starting point for building graphical user interfaces (GUIs) in Python. Let's break it down into a comprehensive guide, from the basics to more advanced text manipulation.

The Absolute Basics: Tk and Toplevel
First, you need to understand the two main windows you can create.
tk.Tk(): This creates the main application window. Your application should have only oneTkinstance. It's the root of your GUI.tk.Toplevel(): This creates a secondary window. You can create as many of these as you need. They are often used for dialogs, pop-ups, or additional content windows.
Example: Creating a main window and a secondary window.
import tkinter as tk
# --- Main Application Window ---
root = tk.Tk()"Main Window")
root.geometry("300x200") # Set size (width x height)
# --- Secondary Window ---
top = tk.Toplevel(root)"Secondary Window")
top.geometry("250x150")
# Add a label to the main window
main_label = tk.Label(root, text="This is the main window.")
main_label.pack(pady=20)
# Add a label to the secondary window
top_label = tk.Label(top, text="This is a Toplevel window.")
top_label.pack(pady=20)
# Start the event loop
root.mainloop()
Displaying Text with Label and Message
The simplest way to display read-only text is with the Label widget. For longer blocks of text that might need wrapping, the Message widget is a good choice (though Label with wraplength is more common now).
Key Options for Labels:

text: The string to display.font: A tuple specifying the font family, size, and style (e.g.,("Helvetica", 14, "bold")).fg(foreground): The color of the text.bg(background): The color of the widget's background.wraplength: The number of characters at which to wrap the text.
import tkinter as tk
root = tk.Tk()"Text Display Example")
# A simple label
label1 = tk.Label(root, text="Hello, Tkinter!", font=("Arial", 24))
label1.pack(pady=10)
# A label with styling and wrapping
label2 = tk.Label(
root,
text="This is a longer piece of text that will wrap automatically when it reaches the edge of the widget, thanks to the wraplength option.",
font=("Courier", 10),
fg="blue",
bg="lightgray",
wraplength=250,
justify="left" # or "center" or "right"
)
label2.pack(pady=10, padx=20, fill="x")
root.mainloop()
Creating Editable Text with Text Widget
This is the core of "text" in Tkinter. The Text widget is a powerful component for creating anything from simple text boxes to full-fledged document editors.
Basic Text Widget
import tkinter as tk
root = tk.Tk()"Text Widget Demo")
# Create a Text widget
text_widget = tk.Text(root, height=10, width=40, wrap="word")
text_widget.pack(padx=10, pady=10)
# Insert text at a specific position (line 1, character 0)
text_widget.insert("1.0", "Welcome to the Text widget!\n\n")
text_widget.insert("end", "You can type here. This text is added to the end.")
# To prevent the user from deleting the initial text, you can "mark" it
text_widget.mark_set("insert", "1.0") # Move cursor to the start
text_widget.mark_grab("insert") # Make it un-deletable (more advanced use)
root.mainloop()
Key Concepts for the Text Widget:
-
Indexing: Text in a
Textwidget is addressed using a special"line.column"format."1.0": The first character of the first line."end": A special index for the end of the text."insert": A special index for the current cursor position."current": The character closest to the mouse pointer.
-
Inserting Text:
text_widget.insert(index, text): Inserts text at the given index.
-
Deleting Text:
(图片来源网络,侵删)text_widget.delete(start_index, end_index): Deletes text fromstart_indextoend_index.text_widget.delete("1.0", "1.10"): Deletes the first 10 characters of the first line.text_widget.delete("1.0", "end"): Deletes all text.
-
Getting Text:
content = text_widget.get("1.0", "end-1c"): Gets all the text. The-1cis important to get rid of the final newline character that Tkinter adds.
Formatting Text in a Text Widget
This is where Text becomes incredibly powerful. You can apply different formatting (tags) to ranges of text.
The Process:
- Define a
tagwith specific styles (font, color, etc.). - Apply that
tagto a range of text.
import tkinter as tk
root = tk.Tk()"Formatted Text")
text = tk.Text(root, height=10, width=40, wrap="word")
text.pack(padx=10, pady=10)
# --- 1. Define Tags ---
text.tag_config("title", font=("Helvetica", 16, "bold"), foreground="darkblue")
text.tag_config("error", font=("Courier", 12), foreground="red", background="yellow")
text.tag_config("code", font=("Courier", 10), background="#f0f0f0")
# --- 2. Insert and Apply Tags ---
text.insert("1.0", "This is a Title\n\n")
text.tag_add("title", "1.0", "1.11") # Apply "title" tag from line 1, char 0 to line 1, char 11
text.insert("end", "This is a normal sentence.\n")
text.insert("end", "This is an error message.\n")
text.tag_add("error", "4.5", "4.23") # Apply "error" tag to "error message"
text.insert("end", "\nHere is some code:\nprint('Hello, world!')")
text.tag_add("code", "6.0", "end")
# Make the text widget read-only after formatting
text.config(state="disabled")
root.mainloop()
Scrolling Text with Scrollbar
The Text widget doesn't have scrollbars built-in. You must create them and link them manually.
import tkinter as tk
root = tk.Tk()"Scrollable Text")
# Create a Text widget
text = tk.Text(root, height=15, width=50, wrap="word")
text.pack(side="left", fill="both", expand=True)
# Create a Scrollbar
scrollbar = tk.Scrollbar(root, command=text.yview)
scrollbar.pack(side="right", fill="y")
# Link the Text widget to the Scrollbar
text.config(yscrollcommand=scrollbar.set)
# Add some long text to demonstrate scrolling
for i in range(1, 50):
text.insert("end", f"This is line number {i} of our scrollable text widget.\n")
root.mainloop()
Practical Example: A Simple Note-Taking App
Let's combine these concepts into a small, functional application.
import tkinter as tk
from tkinter import filedialog, messagebox
def save_file():
"""Saves the content of the text widget to a file."""
file_path = filedialog.asksaveasfilename(
defaultextension=".txt",
filetypes=[("Text files", "*.txt"), ("All files", "*.*")],
)
if file_path:
try:
with open(file_path, "w") as f:
# Get all text from the widget, excluding the last newline
content = text_box.get("1.0", "end-1c")
f.write(content)
root.title(f"Simple Notes - {file_path}")
except Exception as e:
messagebox.showerror("Error", f"Failed to save file: {e}")
def new_file():
"""Clears the text widget."""
text_box.delete("1.0", "end")
root.title("Simple Notes - Untitled")
# --- Main Application ---
root = tk.Tk()"Simple Notes - Untitled")
root.geometry("600x500")
# --- Menu Bar ---
menu_bar = tk.Menu(root)
root.config(menu=menu_bar)
# File Menu
file_menu = tk.Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="New", command=new_file)
file_menu.add_command(label="Open...", command=save_file) # For simplicity, using save for open
file_menu.add_separator()
file_menu.add_command(label="Save", command=save_file)
file_menu.add_command(label="Exit", command=root.quit)
# --- Text Area with Scrollbar ---
text_box = tk.Text(root, wrap="word")
text_box.pack(side="left", fill="both", expand=True)
scrollbar = tk.Scrollbar(root, command=text_box.yview)
scrollbar.pack(side="right", fill="y")
text_box.config(yscrollcommand=scrollbar.set)
# Start the event loop
root.mainloop()
This guide covers the fundamentals of working with text in Tkinter. From here, you can explore more advanced topics like embedding images in a Text widget, using Text for syntax highlighting, or creating complex forms.
