Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation on Tkinter.Text widget?

What are my options for getting validation with the Tkinter.Text widget? I don't require Text's advanced functionality, just its multiline attribute. Unfortunately, it lacks both textvariable and validate commands, so it seems that I cannot attach some kind of callback that checks things every time the text changes. I'd like to avoid having to bind to <KeyRelease>, as that looks to capture ALL keypresses, including the likes of Shift, Ctrl, etc, keys, and would appear to be a bit of a mess to work right.

I basically just need to check if the Text field is blank or not, and enable/disable an "Ok" button as appropriate (i.e., if no text, then the button is disabled).

In lieu of this, has anyone come across a decent subclass of Entry that adds multiline functionality that is written in Python? There is this, which adds textvariable to Text, but it is written in pure TCL, not Python, and seems like it would be difficult to integrate into my existing Python environment.

like image 504
Kumba Avatar asked Jun 18 '26 09:06

Kumba


1 Answers

The binding to the <KeyRelease> button does not need to be messy, you don't have to check the value of the key pressed but fetch the content of the widget. Keep in mind that it always has a '\n' at the end, so when you retrive the contents don't forget to discard it:

content = text.get(1.0, "end-1c")

Then you just need to change the state of the button based on this value:

import Tkinter as tk

def configure_ok_button(event):
    content = event.widget.get(1.0, "end-1c")
    state = "active" if content else "disabled"
    button.configure(state=state)

root = tk.Tk()
text = tk.Text(root)
button = tk.Button(root, text="Ok", state="disabled")
text.bind("<KeyRelease>", configure_ok_button)
text.pack()
button.pack()
root.mainloop()
like image 142
A. Rodas Avatar answered Jun 20 '26 22:06

A. Rodas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!