Tkinter.Text index expressions and unicode

2019-05-12 18:32发布

Let us consider the following code:

from tkinter import Tk, Text

root = Tk()

text = Text(root)

text.insert("end", "abcdefgh\nабвгґдеє\n一伊依医咿噫欹泆")

print(text.index("1.4+1l"), text.index("1.4+2l"))
print(text.index("3.4-1l"), text.index("3.4-2l"))

Some people (for example me) would expect it to print 2.4 3.4 and 2.4 1.4, because +1l and -1l are supposed to preserve the column if the line is long enough. Instead, it prints 2.2 3.2 and 2.6 1.8. It looks like it depends on the number of bytes needed to encode each character.

Should it be this way? Is it documented somewhere? Should I just use something like

line, column = old_index.split(".")
new_index = text.index(f"{line+1}.{column}")

instead of +1l if I care about columns being preserved?

1条回答
Anthone
2楼-- · 2019-05-12 19:18

The problem seems to be Tk-related, not Python-related:

package require Tk 8.6

pack [text .t]
.t insert end "abcdefgh\nабвгґдеє\n一伊依医咿噫欹泆"

puts "[.t index 1.4+1l] [.t index 1.4+2l]"
puts "[.t index 3.4-1l] [.t index 3.4-2l]"

exit 0

Output:

2.2 3.2
2.6 1.8

So I asked a second question.

查看更多
登录 后发表回答