pythontkintercharacter-limit

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


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?


Solution

  • 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)