希望使用Tkin优化创建条目

2024-09-28 20:53:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我花了两个小时试图缩短这段难看的代码,以便在“customscript#”是我的条目之后立即获取它们的值,我想通过“customscript#.get()”获取值,“rootfr”是我的主框架,s是变量。所以我想知道是否有一种方法,使它与'为'循环或类似的东西,谢谢。你知道吗

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)

Tags: columngridrowinsertentry小时s1customscript
2条回答

我想你可以用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])

相关问题 更多 >