Skip to content
Advertisement

Python Tkinter How to get the image of the Canvas?

As the title says, I need to get the image of a canvas

To get the image of a Label, I simply type

aLable = Label(root,image = AnImage)
aLabel.cget("image")

I can check to see if AmImage is in aLabel using cget() so how do I do the same with the Canvas? cget("image") doesn’t seem to work

Advertisement

Answer

I Found a way to do it, So I will try to explain it

from tkinter import *
from PIL import ImageTk,Image

root = Tk()
An_Image = ImageTk.PhotoImage(Image.open('flower.jpg'))
Test = Canvas(root, width = 1000, height = 1000)
Test.create_image(25,25, image=An_Image, anchor=CENTER, tag = "abc")
Test.place(x=10,y = 10)

A Tag is a name to certain parts of a widget like the Canvas. "abc" is the name of the tag of the image that got created, you can name it however you want, the tag cannot contain spaces and it must be a string tag = "your_string".

Image example

The reason we need to add a tag to the item is this

Test.itemcget(Tag_id, Item) # Tag_id is the Item tag

#example 
Test.itemcget("abc", "image") # this is how I get the image from the Test Canvas

    
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement