I want to add text to a text widget in Tkinter, where each word has a separate tag. 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 ;). The easiest way around this limitation is to use the "splat" or "unpacking" operator.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.