0

From this question: What magic prevents Tkinter programs from blocking in interactive shell? which is answered by @abarnert:

If stdin is a TTY, then, each time it tries to fetch a line with input(), various bits of the code module, the built-in REPL, etc., Python calls any installed PyOS_InputHook instead of just reading from stdin.

*What Tkinter does is similar. It's more complicated because it has to deal with Windows, but on nix it's doing something pretty similar to readline. Except that it's calling Tcl_DoOneEvent each time through the loop.

I got riddled by this behavior. input isn't exactly the same as mainloop of tkinter, therefore, Tcl_DoOneEvent won't be called by input. It's understandable that input and mainloop behave similarly, but input calls PyOS_InputHook instead of Tcl_DoOneEvent.

At the interactive shell when running Python interactively, I use gnome-terminal, running this script:

#main.py
from tkinter import *
win = Tk()
Button(win, command=(lambda:print('pressed'))).pack(side=TOP)

executing the file:

$python3 -i main.py
>>> print("something")       # I didn't press enter here

I get the window on screen and pressing the button 2 times this is what I get in the terminal:

>>> print("something")pressed
pressed

after pressing enter the window responded to events, in terminal again:

>>> print("something")pressed
pressed

something
>>> pressed

Of course, there's no input in main.py, but running Python interpreter interactively does demonstrate the point. Generally, how input and the interactive interpreter obviate the need to call Tk.mainloop()?

Edit: It would be easier to grasp if someone could possibly show us the inner working of input and the interactive interpreter with pseudo-code or Python code.

This might seem to be a duplicate, I hope this question will complement the previous one and add more clarification to it.

GIZ
  • 4,409
  • 1
  • 24
  • 43
  • I can't see anything about this question that is different from the other one. – Bryan Oakley May 21 '17 at 21:25
  • @BryanOakley I forgot to include one thing in my question so I edited the question: *Edit: It would be easier to grasp if someone could possibly show us the inner working of `input` and the interactive interpreter with pseudo-code or Python code.* Also in my first paragraph: *I got riddled by this behavior. `input` isn't exactly the same as `mainloop`...* I stated my confusion. – GIZ May 22 '17 at 07:38
  • As it turned out, behind the scenes, `_tkinter.c` overrides `PyOS_InputHook` to integrate the interpreter's prompt with its event loop: [*"Overriding this hook can be used to integrate the interpreter's prompt with other event loops, as done in the :file:Modules/_tkinter.c in the Python source code."*](https://hg.python.org/cpython/rev/672614d809a1) – GIZ May 22 '17 at 08:20

0 Answers0