您必须做的一些细节可能取决于您在运行 IDLE 的 Shell 后想要做什么。我想知道更多。但是让我们从简单的开始,对 pyshell.main 进行最小的更改,使其与其他代码一起运行。
请注意,在下面使用的 3.6 中,PyShell.py 被重命名为 pyshell.py。另请注意,此处的所有内容都相当于使用 IDLE 的私有内部结构,并且“使用风险自负”。
我假设您想在与您的 tkinter 代码相同的进程(和线程)中运行 Shell。将签名更改为
def main(tkroot=None):
将根创建(查找# setup root)更改为
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 中添加它以使测试(“其他代码”的示例)更容易。
follow 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。