如何在Tkinter中修改文本小部件以获取行间注释

时间:2013-07-01 06:08:21

标签: python tkinter

我想知道是否可以使用tkinter创建一个可以处理行间输入的文本框。我需要能够将不同的行“连接”到彼此,并且每行的行为可以是独立的。这是an example。它来自语言注释程序。我的想法是,如果我有一条线,请说:

this    is      an       example
x.Det   be.V    a.Det    example.N

第一行的间距会自动调整,某些行被修改,以便为第二行中的每个单词留出足够的空间,使其不与第一行中的单词重叠。

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

一种简单的方法是使用固定宽度的字体(例如courrier),其中所有字符的宽度相同,然后通过用空格填充将其格式化为纯文本。

Example output

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()