I’m trying to create an app where a part of it involves a label that dynamically changes and displays the number of characters typed within the textbox every time it gets updated. I couldn’t find any information regarding this and unsure whether this is even possible.
Advertisement
Answer
If you want a simpler solution that requires a bit more work by the caller, look at this:
import tkinter as tk def callback(event): # After 1 ms call `_callback` # That is to make sure that tkinter has handled the keyboard press root.after(1, _callback) def _callback(): # The `-1` is there because when you have `text_widget.get(..., "end")` # It adds a "n" character at then end number_of_chars = len(text_widget.get("1.0", "end")) - 1 print(number_of_chars) root = tk.Tk() text_widget = tk.Text(root) text_widget.pack() text_widget.bind("<Key>", callback) root.mainloop()
This basically binds all keyboard presses to the callback
function. I can’t think of any way to change the text in a text widget without pressing a keyboard button.
Please note that it will only run when a key is pressed so it wouldn’t work if you called text_widget.insert
or text_widget.delete
(@acw1668 found that problem). It is the caller’s responsibility to call _callback
just after they call .insert
/.delete
.