简体   繁体   English

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

[英]Execute user entered Python commands from Tkinter?

I am looking for a way to be able to run a python command from a Tkinter GUI.我正在寻找一种能够从 Tkinter GUI 运行 python 命令的方法。 (I am using python 2.7.) (我正在使用 python 2.7。)

Example:例子:

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()

I would like to type print 'hello' in the entry and when I press Run button it actually runs the command print 'hello'我想在条目中输入print 'hello' ,当我按下Run按钮时,它实际上运行了命令print 'hello'

How is this doable?这如何可行? If it is not, than can I add a command line widget in Tkinter?如果不是,那么我可以在 Tkinter 中添加命令行小部件吗?

If you're looking to evaluate expressions (like print 'hello ) one at a time, eval() is what you're looking for.如果您希望一次计算一个表达式(例如print 'hello ),则eval()就是您要寻找的。

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

Another option is exec() ;另一种选择是exec() ; you'll have to decide whether you like one or the other better for your use case.您必须决定对于您的用例是更喜欢一种还是另一种。 The possible dangers have already been described better than I might be able to:可能的危险已经比我所能描述的更好:

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.如果您导入了 eval(input()) 和 os,则某人可以输入 input() os.system('rm -R *') 这将删除您主目录中的所有文件。 Source: CoffeeRain资料来源: CoffeeRain

Do note (as stovfl mentioned) that you ought to declare and pack your widgets separately.请注意(如 stovfl 所述)您应该分别声明和打包您的小部件。

That is, change this:也就是说,改变这个:

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

to this:对此:

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

Otherwise, you end up storing the value of pack() (which is None ) instead of storing your widgets (the Button and Entry objects)否则,您最终会存储pack()的值(即None )而不是存储您的小部件( ButtonEntry对象)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM