How to restrict the amount of characters in a Text() Tkinter box?

204 views Asked by At

I've looked for many answers but have only found ones that show how to do it for Entry(). Here I would like to limit the number of characters to 200 but I don't know how to do so.

from tkinter import *

window = Tk()
window.geometry("800x600")

msgText = Text(window, width = 42, height = 13, font = ('Arial', 10), wrap=WORD)
msgText.grid(row = 1, column = 0, columnspan = 2, padx = 30, pady = 5)

window.mainloop()

Can anyone help me by either showing me how to do this or linking a question like this?

2

There are 2 answers

0
JRiggles On BEST ANSWER

Here's a quick example using a Text widget with a character count function bound to '<KeyPress>' (a.k.a. '<Key>') and '<KeyRelease>' events. Binding to both events (in my experience) keeps the count accurate in situations where keys are held/repeating and so on.

Note: I've made a few minor changes for better adherence to best-practices.

import tkinter as tk


def char_count(event):
    """This function allows typing up to the character limit and allows deletion"""
    count = len(msg_text.get('1.0', 'end-1c'))
    if count >= CHAR_LIMIT and event.keysym not in {'BackSpace', 'Delete'}:
        return 'break'  # dispose of the event, prevent typing


window = tk.Tk()
window.geometry("800x600")
CHAR_LIMIT = 200

# PRO TIP: don't use camelCase for Python variable names
msg_text = tk.Text(window, width=42, height=13, font=('Arial', 10), wrap=WORD)
msg_text.grid(row=1, column=0, columnspan=2, padx=30, pady=5)

msg_text.bind('<KeyPress>', char_count)
msg_text.bind('<KeyRelease>', char_count)

window.mainloop()

Note that this will block all key presses other than Delete or BackSpace once the character limit is reached! I'll leave it to you to figure out how to discriminate which keypresses are allowed (hint: the string class str has a number of methods for this sort of thing)

1
Pragmatic_Lee On

You could set up a function that counts the number of key entries and call that function after each entry.

from tkinter import *

window = Tk()
window.geometry("800x600")

msgText = Text(window, width = 42, height = 13, font = ('Arial', 10), wrap=WORD)
msgText.grid(row = 1, column = 0, columnspan = 2, padx = 30, pady = 5)
def count_entries(e):
    entries = msgText.get('1.0',END)
    count = len(entries)
    # Probably want to count the number of line breaks (\n) and remove them from the count
    if count > 200:
        msgText.delete('end-2c')
msgText.bind('<KeyRelease>',count_entries)


window.mainloop()

Frankly, I'd consider using a different widget such as Message