Python 在Tkinter中使用变量作为索引
如何使用变量作为“.get(startindex[,endindex])”表达式中的索引,而不是数字? 我想要这样的东西:Python 在Tkinter中使用变量作为索引,python,variables,tkinter,indexing,Python,Variables,Tkinter,Indexing,如何使用变量作为“.get(startindex[,endindex])”表达式中的索引,而不是数字? 我想要这样的东西: for i in range(1, n): a = text.get("i.0", "i.end" ) b = text.get("i+1.0", "i+1.end" ) 而不是: a = text.get("1.0", "1.end" ) b = text.get("2.0", "2.end" ) a = text.get(
for i in range(1, n):
a = text.get("i.0", "i.end" )
b = text.get("i+1.0", "i+1.end" )
而不是:
a = text.get("1.0", "1.end" )
b = text.get("2.0", "2.end" )
a = text.get("3.0", "3.end" )
b = text.get("4.0", "4.end" ) etc...
在第一个代码序列中,我得到了“坏文本索引”I.0“错误。仅此信息很难说其目的是什么,但直接回答您的问题时,您可以使用字符串插值,例如。格式方法:
for i in range(1, n):
a = text.get("{0}.0".format(i), "{0}.end".format(i) )
b = text.get("{0}.0".format(i + 1), "{0}.end".format(i + 1))
python提供了三向字符串格式
text.get("%d.0"%(i + 1), "%.end"%(i)) # 1
text.get("{0}.0".format(i), "{0}.end".format(i) ) # 2
text.get(f"{i+1}.0", f"{i}.end") # 3