想要使用 Tkinter 优化创建条目
Wanted to optimize creating Entries using Tkinter
我花了两个小时试图缩短这段丑陋的代码,以便在之后立即获得它们的价值,'customscript#' 是我的条目我想通过 'customscript#.get()'、'rootfr'是我的主框架,s#是变量。所以我想知道是否有办法用 'for' 循环或类似的方法来实现它,谢谢。
customscript1 = Entry(rootfr)
customscript1.insert(0, s1)
customscript1.grid(column = 3, row = 1)
customscript2 = Entry(rootfr)
customscript2.insert(0, s1)
customscript2.grid(column = 3, row = 2)
customscript3 = Entry(rootfr)
customscript3.insert(0, s1)
customscript3.grid(column = 3, row = 3)
customscript4 = Entry(rootfr)
customscript4.insert(0, s1)
customscript4.grid(column = 3, row = 4)
customscript5 = Entry(rootfr)
customscript5.insert(0, s1)
customscript5.grid(column = 3, row = 5)
customscript6 = Entry(rootfr)
customscript6.insert(0, s1)
customscript6.grid(column = 3, row = 6)
我猜你可以使用 locals()
或 globals()
。
local_dict = locals()
for index in xrange(1, 7):
local_dict['customscript%d' % index] = entry = Entry(rootfr)
entry.insert(0, s1)
entry.grid(column = 3, row = index)
函数参考:
https://docs.python.org/2/library/functions.html#globals
https://docs.python.org/2/library/functions.html#locals
或者您可以简单地使用一个列表来存储所有这些自定义脚本,因为我严重怀疑您是否真的需要一堆编号的变量。根据经验,如果您发现自己被迫编写丑陋的代码,那么问题出在代码架构中。
您可以将条目存储在列表或字典中。我发现字典很方便,因为它们可以是稀疏的(即:您不必从零开始计数):
entries = {}
for row in range(1,7):
e = Entry(rootfr)
e.insert(0, s1)
e.grid(column = 3, row = 1)
entries[row] = e
稍后您可以通过它们的索引访问它们:
for row in range(1, 7):
print("row %s has the value %s" % (row, entries[row])
我花了两个小时试图缩短这段丑陋的代码,以便在之后立即获得它们的价值,'customscript#' 是我的条目我想通过 'customscript#.get()'、'rootfr'是我的主框架,s#是变量。所以我想知道是否有办法用 'for' 循环或类似的方法来实现它,谢谢。
customscript1 = Entry(rootfr)
customscript1.insert(0, s1)
customscript1.grid(column = 3, row = 1)
customscript2 = Entry(rootfr)
customscript2.insert(0, s1)
customscript2.grid(column = 3, row = 2)
customscript3 = Entry(rootfr)
customscript3.insert(0, s1)
customscript3.grid(column = 3, row = 3)
customscript4 = Entry(rootfr)
customscript4.insert(0, s1)
customscript4.grid(column = 3, row = 4)
customscript5 = Entry(rootfr)
customscript5.insert(0, s1)
customscript5.grid(column = 3, row = 5)
customscript6 = Entry(rootfr)
customscript6.insert(0, s1)
customscript6.grid(column = 3, row = 6)
我猜你可以使用 locals()
或 globals()
。
local_dict = locals()
for index in xrange(1, 7):
local_dict['customscript%d' % index] = entry = Entry(rootfr)
entry.insert(0, s1)
entry.grid(column = 3, row = index)
函数参考:
https://docs.python.org/2/library/functions.html#globals
https://docs.python.org/2/library/functions.html#locals
或者您可以简单地使用一个列表来存储所有这些自定义脚本,因为我严重怀疑您是否真的需要一堆编号的变量。根据经验,如果您发现自己被迫编写丑陋的代码,那么问题出在代码架构中。
您可以将条目存储在列表或字典中。我发现字典很方便,因为它们可以是稀疏的(即:您不必从零开始计数):
entries = {}
for row in range(1,7):
e = Entry(rootfr)
e.insert(0, s1)
e.grid(column = 3, row = 1)
entries[row] = e
稍后您可以通过它们的索引访问它们:
for row in range(1, 7):
print("row %s has the value %s" % (row, entries[row])