“input”如何替代tkinter mainloop?

2024-04-19 19:13:50 发布

您现在位置:Python中文网/ 问答频道 /正文

从这个问题: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 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.

我被这种行为弄糊涂了。input与tkinter的mainloop不完全相同,因此Tcl_DoOneEvent不会被input调用。可以理解,inputmainloop的行为类似,但是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和交互式解释器的内部工作,那就更容易理解了。

这似乎是一个重复,我希望这个问题将补充前一个问题,并增加更多的澄清。你知道吗


Tags: thetofrompyinputmainittcl