I would like to set or clear the invalid
state flag of a ttk.Entry
whenever the contents change. I'm doing this by connecting a StringVar
to the entry, and in a trace()
callback, calling state(['valid'])
or state(['!invalid'])
. The flag is correctly set by my callback, but then, whenever the focus leaves the text entry, it's cleared! How can I avoid or work around this?
I want to set or clear the flag because I can change the visual style based on the state flags. I don't want to disallow the user from typing anything invalid; I want them to be free to type whatever they want, and see immediately if it's valid or not. I want to use the invalid
flag specifically, not the alternate
flag, not only because invalid
is the more logical choice, but also because I'm already using the alternate
flag for something else.
I'm not using the built-in validation capabilities of this widget, because, according to the Tk docs, if I invoke the validation command whenever the text is edited (-validate
equal to 'keys'
or 'all'
),
The entry will be prevalidated prior to each edit ... If prevalidation fails, the edit is rejected.
Like I said before, I don't want that. I want what -validate
equal to 'none'
is supposed to do:
validation will only occur when specifically requested by the
validate
widget command.
Great, so in theory all I have to do is never call validate()
. Unfortunately, the invalid
flag is being cleared anyway. I can reproduce this unexpected and unwanted behavior in Python's interactive mode:
>>> import tkinter as tk
>>> from tkinter import ttk
>>> win = tk.Tk()
>>> entry = ttk.Entry(win)
>>> entry.pack()
>>> entry['validate']
'none'
>>> entry.state()
()
>>> entry.state(['invalid'])
('!invalid',)
>>> entry.state()
('invalid',)
So far, so good. (I'm using Python 3 in this example, but I get the same results with Python 2.) Now I change focus to and from my entry box, and:
>>> entry.state()
()
Why is it getting cleared, when -validate
is 'none'
, not 'focus'
or 'all'
? Is there anything I can do to use the invalid
state for my purposes?
I see this same behavior with both Python 3.4.2 and 2.7.9, using Tcl/Tk version 8.6, on Linux.