这个问题可能已经得到解答,但经过长时间搜索和网络我没有找到合适的答案。
我有 3 个连续循环,如下所示:
w = my_text0.get(1.0, END).split()
data = []
# get & set the matching dict keys and values
for i in w:
if i in [*dictionary]:
word = i.title()
my_text.insert(END, word)
my_text.insert(END, ", " + dictionary[i] + "\n")
keys_len = len(word)
print("keys_len", keys_len)
data.append(keys_len)
print("data", data)
# print("keys_len", keys_len)
# get text widget lines count
txtwidg_lnescnt = int(my_text.index("end-1c").split(".")[0])
for j in range(0, len(data)):
k_l = data[j]
print("k_l", k_l)
print("k_l out", k_l)
# get index start and end for tag_add method
for k in range(1, txtwidg_lnescnt):
lne_idx = k
str_idx = f"{lne_idx}.0"
end_idx = f"{lne_idx}.{k_l}"
print("end_idx", end_idx)
my_text.tag_add("start", str_idx, end_idx)
my_text.tag_config(
"start",
background="red",
foreground="black",
font=bdfont,
)
我需要在 中处理 中k_l
的值。但目前仅处理最后一个值。2nd loop
3rd loop
(9)
2nd loop
这是我得到的输出:
keys_len 5
keys_len 6
keys_len 9
data [5, 6, 9]
k_l 5
k_l 6
k_l 9
k_l out 9
end_idx 1.9
end_idx 2.9
end_idx 3.9
我需要它是这样的:
keys_len 5
keys_len 6
keys_len 9
data [5, 6, 9]
k_l 5
k_l 6
k_l 9
k_l out 9
end_idx 1.5
end_idx 2.6
end_idx 3.9
我熟悉append to an empty list method
存储循环中的所有值。
但我不能在这里重复它,因为它已经在1st loop
.
我也尝试使用,return from a separate function method
但它输出为嵌套循环,这不是我需要的:
def mykeyslengths():
# get the user's entered words
w = my_text0.get(1.0, END).split()
data = []
# get & set the matching dict keys and values
for i in w:
word = i
keys_len = len(word)
print("keys_lenzz", keys_len)
data.append(keys_len)
for j in range(0, len(data)):
k_l = data[j]
print("k_l", k_l)
return k_l
def generate():
# Clear The text
my_text.delete(1.0, END)
# get the user's entered words
w = my_text0.get(1.0, END).split()
# data = []
# get & set the matching dict keys and values
for i in w:
if i in [*dictionary]:
word = i.title()
my_text.insert(END, word)
my_text.insert(END, ", " + dictionary[i] + "\n")
# keys_len = len(word)
# print("keys_len", keys_len)
# data.append(keys_len)
# print("data", data)
# print("keys_len", keys_len)
# get text widget lines count
txtwidg_lnescnt = int(my_text.index("end-1c").split(".")[0])
# for j in range(0, len(data)):
# k_l = data[j]
# print("k_l", k_l)
# print("k_l out", k_l)
# get index start and end for tag_add method
for k in range(1, txtwidg_lnescnt):
lne_idx = k
str_idx = f"{lne_idx}.0"
end_idx = f"{lne_idx}.{mykeyslengths()}"
print("end_idx", end_idx)
my_text.tag_add("start", str_idx, end_idx)
my_text.tag_config(
"start",
background="red",
foreground="black",
font=bdfont,
)
哪个输出如下:
keys_lenzz 5
keys_lenzz 6
keys_lenzz 9
k_l 5
k_l 6
k_l 9
end_idx 1.9
keys_lenzz 5
keys_lenzz 6
keys_lenzz 9
k_l 5
k_l 6
k_l 9
end_idx 2.9
keys_lenzz 5
keys_lenzz 6
keys_lenzz 9
k_l 5
k_l 6
k_l 9
end_idx 3.9
如果示例中还不清楚这一点,我需要长度5, 6, 9
并bold
修改backgrounds
由具有结束索引属性的变量值foregrounds
确定的各个子字符串长度。end_idx
tkinter
tag_add
我当前遇到的问题是,所有 3 个子字符串(字典键)的长度相同 (9),而它们根据各自的长度 (5、6、9) 应该是不同的。
这应该有效: