您必须执行的操作的一些细节可能取决于 IDLE Shell 运行后您想要对其执行的操作。我想了解更多相关信息。但让我们从简单开始,对 pyshell.main 进行最小的更改,使其与其他代码一起运行。
请注意,在我下面使用的 3.6 中,PyShell.py
被重命名pyshell.py
。另请注意,这里的所有内容都相当于使用 IDLE 的私有内部结构,并且“使用风险由您自行承担”。
我假设您想在与 tkinter 代码相同的进程(和线程)中运行 Shell。将签名更改为
def main(tkroot=None):
更改根创建(查找# setup root
) to
if not tkroot:
root = Tk(className="Idle")
root.withdraw()
else:
root = tkroot
在当前的 3.6 中,还有几行需要缩进if not tkroot
:
if use_subprocess and not testing:
NoDefaultRoot()
保护主循环并销毁(最后)
if not tkroot:
while flist.inversedict: # keep IDLE running while files are open.
root.mainloop()
root.destroy()
# else leave mainloop and destroy to caller of main
上面将根窗口的“依赖注入”添加到函数中。我可能会在 3.6 中添加它以使测试(“其他代码”的示例)更容易。
现在运行以下 tkinter 程序,显示根窗口和 IDLE shell。
from tkinter import *
from idlelib import pyshell
root = Tk()
Label(root, text='Root id is '+str(id(root))).pack()
root.update()
def later():
pyshell.main(tkroot=root)
Label(root, text='Use_subprocess = '+str(pyshell.use_subprocess)).pack()
root.after(0, later)
root.mainloop()
您应该可以随时调用 pyshell.main 。