Search code examples
pythonpython-2.7tkintertkinter-entry

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. (I am using 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'

How is this doable? If it is not, than can I add a command line widget in Tkinter?


Solution

  • If you're looking to evaluate expressions (like print 'hello) one at a time, eval() is what you're looking for.

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

    Another option is 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. Source: CoffeeRain

    Do note (as stovfl mentioned) that you ought to declare and pack your widgets separately.

    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)