pythontkintereval

Calling eval with a variable of type string returns an error


I have a problem with the eval function in python. I have a window in tinker that returns me a string value. I pass them to eval and I get a syntax error. In the name field, enter 'abc'. Why?

from tkinter import *
from tkinter.messagebox import showerror

fieldnames = ('name', 'age', 'job', 'pay')



def makeWidgets():
    global entries
    window = Tk()
    window.title('People Shelve')
    form = Frame(window)
    form.pack()
    entries = {}
    for (ix, label) in enumerate(('key',) + fieldnames):
        lab = Label(form, text=label)
        ent = Entry(form)
        lab.grid(row=ix, column=0)
        ent.grid(row=ix, column=1)
        entries[label] = ent
    Button(window, text="Update", command=updateRecord).pack(side=LEFT)
    Button(window, text="Quit", command=window.quit).pack(side=RIGHT)
    return window



def updateRecord():
    for field in fieldnames:
        text = entries[field].get()
        eval(text) # ERROR invalid syntax

window = makeWidgets()
window.mainloop()

I want to find out why I'm getting an error. I want this error explained to me.


Solution

  • The problem is that if some of your fields are empty, entries[field].get() will return an empty string "". So you will try to evaluate an empty string (eval('')), which you can't do. This results in the error you see. You can fix this in different ways, for example, check if the text is not empty string, like this:

    text = entries[field].get()
    if text != '':
        eval(text)
    

    Or you can add try except block, like this:

    text = entries[field].get()
    try:
        eval(text)
    except SyntaxError:
        print("no values in a field")
    except NameError:
        print("text must be entered as 'some text'")