user18760311
user18760311

Reputation:

Add tag to Tkinter PhotoImage

I'm writing a program that creates a new canvas item, with a specific image depending on a certain variable. Here's an example of what I'm after, with >>>>tag<<<< representing (preferably a string) linked to one of those PhotoImages:

image = PhotoImage(file="File.png")
image_2 = PhotoImage(file="File_2.png")
output = >>>>tag<<<<
c.create_image(0, 0, image=output)

So far, I have been unable to find a way to link a PhotoImage item to a tag or some way of relating it to a different variable. The only other way to do what I want to do would be to create a huge line of "if" statements which would be extremely time-consuming and unnecessary. So any method of tagging would be extremely helpful. Thanks.

Upvotes: 0

Views: 590

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386020

The canvas supports associating tags with a canvas item. For example, to add the tag "meta" to the image you would do something like this:

c.create_image(0, 0, image=output, tags=("meta",))

In addition to setting the tags option when creating an item, there are many methods on the canvas for working with tags. Though, almost all are just specializations of calling addtag with a special argument. For example, addtag_above('foo', 'bar') is the same as calling addtag('foo', 'above', 'bar')

  • addtag
  • addtag_above
  • addtag_all
  • addtag_below
  • addtag_closest
  • addtag_closest
  • addtag_enclosed
  • addtag_overlapping
  • addtag_withtag

In addition, you can use the options itemconfig and itemcget.

Upvotes: 0

Related Questions