[Python/Tkinter]How can I fetch the value of data which was set in function “event_generate”

北战南征 提交于 2019-12-06 02:01:10

No, unfortunately it doesn't. The Tcl interpreter recognizes it as a valid option, but it is one of the missing options that are not included in the Event class, like warp. You can take a look at the line 1188 of the Tkinter source code to see the rest of the missing options.

Tkinter does not handle properly the data field of event_generate.

Here is a snippet using private API of Tkinter (in fact Tcl...) that allows to read this field. This function only works with literals and I usually pass data a dictionary with literals.

from Tkinter import *

def handle_it(event):
    # print "event handler"
    print event.data

def bind_event_data(widget, sequence, func, add = None):
    def _substitute(*args):
        e = lambda: None #simplest object with __dict__
        e.data = eval(args[0])
        e.widget = widget
        return (e,)

    funcid = widget._register(func, _substitute, needcleanup=1)
    cmd = '{0}if {{"[{1} %d]" == "break"}} break\n'.format('+' if add else '', funcid)
    widget.tk.call('bind', widget._w, sequence, cmd)

root = Tk()

# unfortunately, does not work with my snippet (the data argument is eval-ed)
# you can adapt it to handle raw string.
root.after(100, lambda : root.event_generate('<<test>>', data="hi there"))
# works, but definitely looks too hacky
root.after(100, lambda : root.event_generate('<<test>>', data="'hi there'"))
# the way I typically use it
root.after(100, lambda : root.event_generate('<<test>>', data={"content": "hi there"}))

#should be:
#  root.bind('<<test>>', handle_it)
bind_event_data (root, '<<test>>', handle_it)

root.mainloop()

Note: there seems to be a race condition that prevent the event to be catched with a too small delay in after.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!