tkinter keep only part of a text editable in python

To keep only part of a text editable in tkinter, you can use the Tkinter Text widget and configure different tags for the editable and non-editable parts of the text.

Here's an example on how you can achieve this:

main.py
import tkinter as tk

def toggle_editable(event):
    text.tag_config("editable", state=tk.NORMAL if not text.tag_ranges("editable") else tk.DISABLED)

root = tk.Tk()

text = tk.Text(root)
text.pack()

# Insert the text with editable and non-editable parts
text.insert(tk.END, "This is editable. ")
text.insert(tk.END, "This is not editable.", "non_editable")

# Configure the tag for the non-editable part
text.tag_configure("non_editable", state=tk.DISABLED)

# Toggle the editable state when the user clicks on the text
text.bind("<Button-1>", toggle_editable)

root.mainloop()
581 chars
22 lines

In this example, we create a Text widget and insert the text with editable and non-editable parts. We configure a tag called "non_editable" with tag_configure and set its state to DISABLED to make it non-editable.

We also bind a mouse click event listener to the Text widget. This listener calls the toggle_editable() function when the user clicks on the text.

The toggle_editable() function checks if there are any ranges defined for the "editable" tag using tag_ranges(). If there are no ranges, it means the text is currently editable. In that case, it sets the state of the "editable" tag to NORMAL (editable). If there are ranges, it means the text is not editable. In that case, it sets the state of the "editable" tag to DISABLED (non-editable).

By clicking on the text, the user can toggle the editable state of the text, allowing them to edit only the parts tagged as "editable".

related categories

gistlibby LogSnag