我想知道是否可以使用 tkinter 创建一个可以处理行间输入的文本框。我需要能够将不同的线路“连接”到彼此,并且每条线路的行为可以是独立的。这是一个例子。它来自语言注释程序。这个想法是,如果我有一条线,请说:
this is an example
x.Det be.V a.Det example.N
第一行的间距是自动调整的,有些行被修改,以便为第二行中的每个单词留出足够的空间,以免与第一行中的单词重叠。
有没有办法做到这一点?
一个简单的方法是使用一个固定宽度的字体(例如 courier),其中所有字符的宽度都相同,然后通过用空格填充将其格式化为纯文本。
from Tkinter import *
sentence = [ 'this', 'is', 'an', 'example' ]
result = [ 'x.Det', 'be.V', 'a.Det', 'example.N' ]
line_start = [0, len(sentence)] # Used to split the sentence into lines no longer than line_len
line_len = 20 # Max characters in each line, including extra spaces
segment_len = 0
for i in range(len(sentence)):
s_len = len(sentence[i])
r_len = len(result[i])
# Pad words (or word groups) so the segments of sentence and result have the same width
if s_len > r_len:
result[i] += ' ' * s_len - r_len
elif s_len < r_len:
sentence[i] += ' ' * (r_len - s_len)
segment_len += max(r_len, s_len) + 1
# Check the line length
if segment_len > line_len:
segment_len = 0
line_start.insert(1, i)
root = Tk()
for i in range(len(line_start)-1):
sentence_segment = ' '.join( sentence[line_start[i]:line_start[i+1]] )
ts = Text(root, font='TkFixedFont', width = line_len, height = 1)
ts.insert(END, sentence_segment)
ts.pack()
result_segment = ' '.join( result[line_start[i]:line_start[i+1]] )
tr = Text(root, font='TkFixedFont', width = line_len, height = 1, foreground='grey')
tr.insert(END, result_segment)
tr.pack()
root.mainloop()