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

2024-06-26 17:48:34 发布

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

我正在寻找一种能够从tkintergui运行python命令的方法。(我使用的是Python2.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',当我按Run按钮时,它实际上运行命令print 'hello'

这怎么可能?如果不是,那么我可以在Tkinter中添加一个命令行小部件吗?你知道吗


Tags: runtext命令tkinterdefbuttonrootcommand
1条回答
网友
1楼 · 发布于 2024-06-26 17:48:34

如果您希望一次计算一个表达式(如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对象)

相关问题 更多 >