从这个问题:What magic prevents Tkinter programs from blocking in interactive shell?由@abarnert回答:
If stdin is a TTY, then, each time it tries to fetch a line with
input()
, various bits of thecode
module, the built-in REPL, etc., Python calls any installedPyOS_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 toreadline
. Except that it's callingTcl_DoOneEvent
each time through the loop.
我被这种行为弄糊涂了。input
与tkinter的mainloop
不完全相同,因此Tcl_DoOneEvent
不会被input
调用。可以理解,input
和mainloop
的行为类似,但是input
调用PyOS_InputHook
而不是Tcl_DoOneEvent
。你知道吗
在交互式运行Python时的交互式shell中,我使用gnome-terminal
,运行以下脚本:
#main.py
from tkinter import *
win = Tk()
Button(win, command=(lambda:print('pressed'))).pack(side=TOP)
执行文件:
$python3 -i main.py
>>> print("something") # I didn't press enter here
我在屏幕上看到窗口,按下按钮两次,这就是我在终端上看到的:
>>> print("something")pressed
pressed
按enter键后,窗口对事件做出响应,再次在终端中:
>>> print("something")pressed
pressed
something
>>> pressed
当然,在main.py
中没有input
,但是以交互方式运行Python解释器确实证明了这一点。一般来说,input
和交互式解释器如何避免调用Tk.mainloop()
?你知道吗
编辑:
如果有人能用伪代码或Python代码向我们展示input
和交互式解释器的内部工作,那就更容易理解了。
这似乎是一个重复,我希望这个问题将补充前一个问题,并增加更多的澄清。你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐