如何在Tkinter中解决tag_add的问题

问题描述 投票:0回答:1

我想标记要插入字符串的特定日期。我使用tag_add来执行此操作...我不知道为什么,但是代码无法正常运行。您可以检查哪里可能有问题。

    from tkinter import *
from tkinter import Text #renames to ttk
import tkinter.messagebox
import calendar

text = Text()
text.pack()
text.tag_configure("dan", background='light grey', foreground='blue')

# Display calendar
month = calendar.month(2020, 2, 2, 1)
text.insert('1.0', month)

# Get a day, index of a day in the string month, and then color the day
datum = "2020 02 11"
d = datum.split()
y = int(d[0])
m = int(d[1]) 
day = d[2]
day = month.find(day)
text.tag_add('dan', f"{day}.18", f"{day}.20") # ?? Maybe problem here??

text.mainloop()

祝您一切顺利,Domen

python tkinter tags
1个回答
0
投票

您的month.find()返回83。这是字符串开始索引11,但是您可能要执行的操作是将month拆分为行列表。可以用splitlines()完成。然后,我们在for循环中编写代码,检查哪一行包含一天,然后从row.find()处获取正确的列索引。

试一下,如果您有任何疑问,请告诉我:

import tkinter as tk
import calendar

root = tk.Tk()
text = tk.Text()
text.pack()
text.tag_configure("dan", background='light grey', foreground='blue')
month = calendar.month(2020, 2, 2, 1)
text.insert('1.0', month)
datum = "2020 02 11"
d = datum.split()
y = int(d[0])
m = int(d[1])
day = d[2]

row_index = 0
col_index = 0
for row in month.splitlines():
    row_index += 1
    if day in row:
        col_index = row.find(day)
        break

text.tag_add('dan', '{}.{}'.format(row_index, col_index), '{}.{}'.format(row_index, col_index + len(day)))
text.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.