如何使用 idlelib.PyShell 在 tkinter 程序中嵌入解释器?
How to use idlelib.PyShell to embed an interpreter in a tkinter program?
我需要在我的 tkinter 程序中嵌入一个交互式 python 解释器。谁能帮我看看如何整合它?
我已经看过 main()
函数,但它对我的需求来说太复杂了,但我似乎无法在不破坏它的情况下减少它。
您必须执行的操作的一些细节可能取决于您在获得 IDLE Shell 运行ning 后要执行的操作。我想知道更多。但是让我们从简单开始,对 pyshell.main 进行最少的更改,使其与其他代码一起 运行。
请注意,在我下面使用的 3.6 中,PyShell.py
已重命名为 pyshell.py
。另请注意,此处的所有内容都相当于使用 IDLE 的私有内部结构,并且是 'use at your own risk'.
我假设您想 运行 Shell 在与您的 tkinter 代码相同的进程(和线程)中。将签名更改为
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
上面在函数中添加了根window的'dependency injection'。我可能会在 3.6 中添加它以使测试('other code' 的示例)更容易。
跟随 tkinter 程序现在 运行s,同时显示根 window 和 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。
我需要在我的 tkinter 程序中嵌入一个交互式 python 解释器。谁能帮我看看如何整合它?
我已经看过 main()
函数,但它对我的需求来说太复杂了,但我似乎无法在不破坏它的情况下减少它。
您必须执行的操作的一些细节可能取决于您在获得 IDLE Shell 运行ning 后要执行的操作。我想知道更多。但是让我们从简单开始,对 pyshell.main 进行最少的更改,使其与其他代码一起 运行。
请注意,在我下面使用的 3.6 中,PyShell.py
已重命名为 pyshell.py
。另请注意,此处的所有内容都相当于使用 IDLE 的私有内部结构,并且是 'use at your own risk'.
我假设您想 运行 Shell 在与您的 tkinter 代码相同的进程(和线程)中。将签名更改为
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
上面在函数中添加了根window的'dependency injection'。我可能会在 3.6 中添加它以使测试('other code' 的示例)更容易。
跟随 tkinter 程序现在 运行s,同时显示根 window 和 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。