2

I am trying to get values from a Tkinter Entry() widget, but it returns that str() has no attribute get():

import tkinter
from tkinter import * 
root=Tk()
flag=0
a={'x','y','z'}  # Consider these as columns in database
for i in a:
    i=Entry(root)
    i.pack()
def getter():
    for i in a:
        b=i.get()  # i is read as string and not as variable                    
        print(b)
asdf=Button(root,text='Enter',command=getter)
asdf.pack()
root.mainloop()    
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Possible duplicate of [How do I do variable variables in Python?](http://stackoverflow.com/questions/1373164/how-do-i-do-variable-variables-in-python) – jonrsharpe Oct 07 '15 at 13:40

1 Answers1

0

This code is the problem:

def getter():
    for i in a:
        b=i.get()     #i is read as string and not as variable

a is a set comprised of three strings. When you iterate over it, i will be a string. Therefore, when you call i.get() you're trying to call .get() on a string.

One solution is to store your entry widgets in a list, so you can iterate over that instead:

widgets = []
for i in a:
    i=Entry(root)
    i.pack()
    widgets.append(i)
...
for i in widgets:
    b=i.get()
    ...

If you want the widgets to be associated with the letters, use a dictionary:

widgets = {}
for i in a:
    i=Entry(root)
    i.pack()
    widgets[a] = i
...
for i in a:
    b=widgets[i].get()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685