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
Selected Reading
How to make the Tkinter text widget read only?
In Tkinter, you can make a text widget read-only by setting its state configuration to DISABLED. This prevents users from editing the content while keeping it visible and readable.
Making Text Widget Read-Only
Use the config() method to change the state of a text widget ?
from tkinter import *
# Create an instance of window
win = Tk()
win.geometry("700x400")
win.title("Read-Only Text Widget")
def disable_button():
text.config(state=DISABLED)
def enable_button():
text.config(state=NORMAL)
# Label
Label(win, text="Type Something", font=('Helvetica bold', 25),
fg="green").pack(pady=20)
# Create a Text widget
text = Text(win, height=10, width=40)
text.pack()
# Create Disable and Enable Buttons
Button(win, text="Make Read-Only", command=disable_button,
fg="white", bg="red", width=20).pack(pady=10)
Button(win, text="Make Editable", command=enable_button,
fg="white", bg="green", width=20).pack(pady=5)
win.mainloop()
Text Widget States
Tkinter text widgets have three possible states ?
| State | Description | User Can Edit? |
|---|---|---|
NORMAL |
Default editable state | Yes |
DISABLED |
Read-only, grayed out | No |
READONLY |
Read-only, normal appearance | No |
Setting Initial Read-Only State
You can create a text widget that starts as read-only ?
from tkinter import *
win = Tk()
win.geometry("500x300")
# Create read-only text widget with initial content
text = Text(win, height=8, width=50, state=DISABLED)
text.pack(pady=20)
# To add content to disabled text widget, temporarily enable it
text.config(state=NORMAL)
text.insert(1.0, "This text widget is read-only.\nYou cannot edit this content.")
text.config(state=DISABLED)
win.mainloop()
Programmatic Content Updates
To update content in a disabled text widget, temporarily enable it ?
from tkinter import *
win = Tk()
win.geometry("600x400")
def update_content():
# Temporarily enable to modify content
text.config(state=NORMAL)
text.delete(1.0, END)
text.insert(1.0, "Content updated programmatically!\nThis widget remains read-only.")
text.config(state=DISABLED)
# Create read-only text widget
text = Text(win, height=10, width=50, state=DISABLED)
text.pack(pady=20)
# Add initial content
text.config(state=NORMAL)
text.insert(1.0, "Initial read-only content")
text.config(state=DISABLED)
# Button to update content
Button(win, text="Update Content", command=update_content,
bg="blue", fg="white", width=20).pack(pady=10)
win.mainloop()
Conclusion
Set state=DISABLED to make a Tkinter text widget read-only. Temporarily enable it with state=NORMAL when you need to update content programmatically. This approach is perfect for displaying information that users should read but not modify.
Advertisements
