执行用户从 Tkinter 输入的 Python 命令?

Execute user entered Python commands from Tkinter?

我正在寻找一种能够从 Tkinter GUI 运行 python 命令的方法。 (我正在使用 python 2.7。)

示例:

import Tkinter
root = Tk()

def run():
   print 'smth'

def runCommand():
   code...

button = Button(root, text = 'smth', command = run).pack()

entry = Entry(root, width = 55, justify = 'center').pack()
entry_button = Button(root, text = 'Run', command = runCommand).pack()

root.mainloop()

我想在条目中输入 print 'hello',当我按下 运行 按钮时,它实际上是 运行 命令 print 'hello'

这是怎么做到的?如果不是,我可以在 Tkinter 中添加命令行小部件吗?

如果您希望一次计算一个表达式(如 print 'hello),eval() 就是您要找的。

def runCommand():
   eval(entry.get())

另一种选择是exec();您必须 decide 无论您更喜欢其中一种还是更适合您的用例。可能的危险已经被描述得比我能描述的更好:

A user can use this as an option to run code on the computer. If you have eval(input()) and os imported, a person could type into input() os.system('rm -R *') which would delete all your files in your home directory. Source: CoffeeRain

请注意(如 stovfl 所述)您应该单独声明和打包您的小部件。

也就是这样改:

entry = Entry(root, width = 55, justify = 'center').pack()

对此:

entry = Entry(root, width = 55, justify = 'center')
entry.pack()

否则,您最终会存储 pack() 的值(即 None),而不是存储您的小部件(ButtonEntry 对象)