[Python-Dev] Event loops, PyOS_InputHook, and Tkinter
Michiel Jan Laurens de Hoon
mdehoon at c2b2.columbia.edu
Fri Nov 11 18:56:57 CET 2005
Martin v. Löwis wrote:
>Before trying to explain the reason, please try to explain the
>problem first. What is it *really* that you want to do which
>you feel you currently can't do?
>
>
Probably I should have started the discussion with this; sorry if I
confused everybody. But here it is:
I have an extension module for scientific visualization. This extension
module opens one or more windows, in which plots can be made. Something
similar to the plotting capabilities of Matlab.
For the graphics windows to remain responsive, I need to make sure that
its events get handled. So I need an event loop. At the same time, the
user can enter new Python commands, which also need to be handled.
To achieve this, I make use of PyOS_InputHook, a pointer to a function
which gets called just before going into fgets to read the next Python
command. I use PyOS_InputHook to enter an event loop inside my extension
module. This event loop handles the window events, and returns as soon
as a new Python command is available at stdin, at which point we
continue to fgets as usual.
While this approach more or less works, there are two problems that I
have run into:
1) What if the user decides to import Tkinter next? Tkinter notices that
PyOS_InputHook is already set, and does not reset it to its own event
loop. Hence, Tkinter's events are not handled. Similarly, if a user
imports Tkinter before my extension module, I don't reset
PyOS_InputHook, so Tkinter's events are handled but not mine. If I were
to reset PyOS_InputHook to my extension module's event loop, then my
events get handled but not Tkinter's.
2) On Windows, many users will use IDLE to run Python. IDLE uses two
Python threads, one for the GUI and one for the user's Python commands.
Each has its own PyOS_InputHook. If I import my extension module (or
Tkinter, for that matter), the user-Python's PyOS_InputHook gets set to
the corresponding event loop function. So far so good. However,
PyOS_InputHook doesn't actually get called:
Between Python commands, the GUI-Python is waiting for the user to type
something, and the user-Python is waiting for the GUI-Python. While the
user-Python is waiting for the GUI-Python thread, no call is made to
PyOS_InputHook, therefore we don't enter an event loop, and no events
get handled. Hence, neither my extension module nor Tkinter work when
run from IDLE.
--Michiel.
--
Michiel de Hoon
Center for Computational Biology and Bioinformatics
Columbia University
1150 St Nicholas Avenue
New York, NY 10032
More information about the Python-Dev
mailing list