Canvas object Tags: not the type I originally gave it

Solution 1:

According to Tk canvas documentation:

Each item may also have any number of tags associated with it. A tag is just a string of characters, and it may take any form except that of an integer. For example, x123 is OK but 123 isn't…

And according to Tkinter Canvas.create_text documentation:

tags=

A tag to attach to this item, or a tuple containing multiple tags.

Also in the same An Introduction to Tkinter, the The Tkinter Canvas Widget section says:

Tags are symbolic names attached to items. Tags are ordinary strings, and they can contain anything except whitespace (as long as they don’t look like item handles).

(Italic emphasis mine.)

It seems like Tkinter/Tk converts the tags parameter to a string if it is not a string nor a tuple.


How about using a dictionary to map tag name to the dictionary:

import tkinter

window = tkinter.Tk()
myCanvas = tkinter.Canvas(window, width = 400, height = 400)
myCanvas.pack()

tag_mapping = {}                                      # <----
tag_mapping['tag1'] = { "id": 1, "name": "test" }     # <----
textItemContents = "asdf"
textItem = myCanvas.create_text(1, 1, tags='tag1', text = textItemContents)

searchTags = myCanvas.gettags(textItem)

print(searchTags) # => ('tag1',)
print(searchTags[0]) # => tag1
print(tag_mapping[searchTags[0]]) # => {'name': 'test', 'id': 1}
print(isinstance(tag_mapping[searchTags[0]], dict)) # => True