[英]How to create dynamic variables in Python 3
I am trying to get values from a Tkinter Entry()
widget, but it returns that str() has no attribute get()
: 我正在尝试从Tkinter Entry()
小部件获取值,但是它返回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()
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. a
是由三个字符串组成的集合。 When you iterate over it, i
will be a string. 当您遍历它时, i
将是一个字符串。 Therefore, when you call i.get()
you're trying to call .get()
on a string. 因此,当您调用i.get()
您尝试在字符串上调用.get()
。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.