我有下面的代码,它可以工作并为我提供每个值。一旦收集到所有值,我似乎无法创建一个列表。我目前一次获取一个值。。!我尝试了以下两种方法:
def numberwritten(self, event, key, index):
self.values = []
if not self.left[index]:
self.box[key].config(fg='black')
self.left[index] = True
self.values.append(self.box[key].get())
print self.values
这只适用于每次只打印一个值,但我想要一个可以分配"n"个变量的列表(每次获得的值的数量随机变化)。
例如,我想做"Value%s"%I=获得的值。
您正在创建小部件行。每一行可能比其他行具有更多或更少的小部件。在某个时刻,您需要获得一个表示每行中数据的列表。你在问,"我怎样才能得到这份清单?"。我说得对吗?
关于这个简单的问题,你一定问了20个问题。问题不在这个或任何其他单个函数中,而是在您的通用体系结构中。一位非常非常聪明的程序员曾经告诉我"如果你想让我理解你的代码,就不要给我看你的代码。给我看看你的数据结构。"。这里的根本问题是,您没有数据结构。如果你不整理你的数据,你就不可能轻易地获取数据。
这个问题没什么难的。为每一行保留一个条目小部件的列表,并在需要值时对该列表进行迭代。下面的伪代码显示了这是多么简单:
class MyApp(object):
def __init__(self):
# this represents your data model. Each item in the
# dict will represent one row, with the key being the
# row number
self.model = {}
def add_row(self, parent, row_number):
'''Create a new row'''
e1 = Entry(parent, ...)
e2 = Entry(parent, ...)
e3 = Entry(parent, ...)
...
# save the widgets to our model
self.model[row_number] = [e1, e2, e3]
def extend_row(self, parent, row_number, n):
'''Add additional widgets to a row'''
for i in range(n):
e = Entry(parent, ...)
self.model[row_number].append(e)
def get_values(row_number):
'''Return the values in the widgets for a row, in order'''
result = [widget.get() for widget in self.model[row_number]]
return result
self.values = []
每次调用numberwritten()
时都会清除列表,因此只打印一个值。全局声明self.values
或在类中的__init__()
函数中声明。
关于在每次循环迭代中打印一个值的格式,请尝试以下操作:
print("Value %i = %s" % (index, self.box[key].get())
编辑:如果你真的想在每次循环迭代中打印整个列表,我从这个答案中借用了以下内容:
# Map items in self.values to strings (necessary if they are not strings).
print("All values: [%s]" % ", ".join(map(str, self.values)))
# Use this if the contents of self.values are strings.
print("All values: [%s]" % ", ".join(self.values))