Pablo Pablo - 4 years ago 182
Python Question

How to make Entry widget respond to Activate event

I'm trying to bind the event type

<Activate>
to a Tkinter
Entry
so that my event handler does something when the
Entry
goes from
tk.DISABLED
to
tk.NORMAL
. However, the following code does not work:

import Tkinter as tk

root = tk.Tk()

frame = tk.Frame(root)
frame.pack()

entry = tk.Entry(frame)
entry.configure(state=tk.DISABLED)
entry.pack()

def activation_handler(event):
print('handled event: {}'.format(event))

entry.bind('<Activate>', activation_handler)

button = tk.Button(frame, text='Toggle enable')
button.pack()

def do():
if entry.cget('state') == tk.NORMAL:
entry.configure(state=tk.DISABLED)
else:
entry.configure(state=tk.NORMAL)

button.configure(command=do)

root.mainloop()


What do I need to do to bind
<Activate>
to an
Entry
widget?

Answer Source

The tkinter <Activate> event doesn't fire when enabling and disabling a widget. From the documentation:

Activate, Deactivate These two events are sent to every sub-window of a toplevel when they change state. In addition to the focus Window, the Macintosh platform and Windows platforms have a notion of an active window (which often has but is not required to have the focus). On the Macintosh, widgets in the active window have a different appearance than widgets in deactive windows. The Activate event is sent to all the sub-windows in a toplevel when it changes from being deactive to active. Likewise, the Deactive event is sent when the window's state changes from active to deactive. There are no useful percent substitutions you would make when binding to these events.

If you want to set a binding for when the state of a widget changes from normal to disabled, you can generate your own event (note that the event uses two angle brackets surrounding the name, to designate that it is a virtual event):

...
entry.bind('<<Activate>>', activation_handler)
...
def do():
    if entry.cget('state') == tk.NORMAL:
        entry.configure(state=tk.DISABLED)
    else:
        entry.configure(state=tk.NORMAL)
        entry.event_generate("<<Activate>>")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download