【问题标题】:Execute user entered Python commands from Tkinter?执行用户从 Tkinter 输入的 Python 命令?
【发布时间】:2019-12-22 22:16:52
【问题描述】:

我正在寻找一种能够从 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',当我按下 Run 按钮时,它实际上会运行命令print 'hello'

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

【问题讨论】:

标签: python python-2.7 tkinter tkinter-entry


【解决方案1】:

如果您要一次评估一个表达式(如 print 'hello),eval() 就是您要找的。​​p>

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

另一个选项是exec();您必须decide,无论您更喜欢哪一种,都适合您的用例。可能的危险已经被描述得比我所能描述的还要好:

用户可以使用此选项在计算机上运行代码。如果你导入了 eval(input()) 和 os,一个人可以输入 input() os.system('rm -R *') ,这将删除你主目录中的所有文件。 来源:CoffeeRain

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

也就是说,改变这个:

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

到这里:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 2017-02-18
    • 2017-07-04
    • 2021-12-06
    • 1970-01-01
    • 2013-02-27
    • 2014-04-20
    相关资源
    最近更新 更多