2015-10-07 24 views
2

我試圖從一個Tkinter的Entry()部件得到的值,但它返回str() has no attribute get()如何在Python中創建動態變量3

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

可能的重複[如何在Python中執行變量變量?](http://stackoverflow.com/questions/1373164/how-do-i-do-variable-variables-in-python) – jonrsharpe

+1

** TL ; DR **:不。 – jonrsharpe

回答

0

這段代碼的問題是:

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

a是由三個字符串組成的集合。當你迭代它時,i將是一個字符串。因此,當您撥打i.get()時,您正試圖對字符串撥打.get()

一種解決方案是保存您的輸入控件列表中,這樣你就可以遍歷,與其:

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

如果你想在小部件與字母相關聯,使用字典:

widgets = {} 
for i in a: 
    i=Entry(root) 
    i.pack() 
    widgets[a] = i 
... 
for i in a: 
    b=widgets[i].get() 
+0

感謝Bryan,我得到了我想要的確切答案,在Stackoverflow上非常好的第一次體驗。 –