简体   繁体   English

Python:将标签分配给Tkinter中的文本

[英]Python: Assigning tags to text in Tkinter

I want to add text to a text widget in Tkinter, where each word has a separate tag. 我想在Tkinter中的文本小部件中添加文本,其中每个单词都有一个单独的标记。 Short example: 简短的例子:

text.insert('end',
    'Hello, ', 'TAG1',
    'how ', 'TAG2',
    'are you.', 'TAG3',)

This gives the output: "Hello, how are you" 这给出了输出:“你好,你好吗”

This works fine, but my problem is that I want to do this with a text spanning several paragraphs. 这很好,但我的问题是我想用跨越几段的文本来做这件事。 I've tried a method where I use a script to edit the text file so that every word is followed by a tag, in the same way as in the above example. 我尝试了一种方法,我使用脚本编辑文本文件,以便每个单词后跟一个标记,方法与上面的例子相同。

But if I paste the text into the script, I get this error: 但是,如果我将文本粘贴到脚本中,我会收到此错误:

There's an error in your program:
*** more than 255 arguments(scriptname.py, line 77)

No traceback, though. 不过没有追溯。

This method doesn't give the desired output either: 此方法也不会提供所需的输出:

infile = open('filepath').read()
text.insert('end', infile)

With the above method the script actually runs, but text in the text widget turns out like this: 使用上面的方法,脚本实际上运行,但文本小部件中的文本结果如下:

'The ', 'TAG1',
'Hundred ', 'TAG2',
'Years', 'TAG3',
'War ', 'TAG4',

And not like this: 'The hundred years war', like it's supposed to, and needless to say the tags aren't assigned to the words. 而不是这样:'百年战争',就像它应该的那样,并且不用说标签没有分配给单词。

Does anyone know if there is a correct way of doing this, or is it simply the case that you can't assign tags to that many words? 有没有人知道是否有正确的方法,或者只是你不能为这么多单词分配标签?

EDIT: clarified a little 编辑:澄清一点

It seems that the number of arguments to a python function are limited to 255 (see here ) -- Apparently Guido thinks it's erroneous to (explicitly) call a function with more arguments than that (I think I agree with him on this point ;). 似乎python函数的参数数量限制为255(参见此处 ) - 显然Guido认为(明确地)调用具有更多参数的函数是错误的(我认为我在这一点上同意他;) 。 The easiest way around this limitation is to use the "splat" or "unpacking" operator. 解决此限制的最简单方法是使用“splat”或“unpacking”运算符。

import Tkinter as tk

words="""this is a really large file, it has a lot of words"""*25

args=['end']
for i,w in enumerate(words.split()):
   args.extend((w+' ','TAG%d'%i))


root=tk.Tk()
text=tk.Text(root)
text.grid(row=0,column=0)
text.insert(*args)
root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM