Jul-08-2021, 04:33 PM
(This post was last modified: Jul-09-2021, 04:13 PM by deanhystad.)
import tkinter as tk root = tk.Tk() canvas = tk.Canvas(root, height=100, width=100) image = tk.PhotoImage(file='some_image_file.png') x = canvas.create_image(50, 50, image=image) y = canvas.create_line(0, 0, 100, 100) canvas.pack() print(x, type(x), y, type(y)) root.mainloop()
Output:1 <class 'int'> 2 <class 'int'>
canvas.create_* returns an int. This is a unique ID for the object that was just created. In my example x is 1 and y is 2. If I created another canvas object it would probably be 3. To Python, the id is just an int and it doesn't provide any methods for configuring the canvas object. To modify the object you use canvas methods and pass the ID of the object you want to modify. This program gets a dictionary of all the options/attributes you can configure for a canvas image object.import tkinter as tk root = tk.Tk() canvas = tk.Canvas(root, height=100, width=100) canvas.pack() image= tk.PhotoImage(file='image.png') x = canvas.create_image(50, 50, image=image) config_items = canvas.itemconfigure(x) # Call without option arguments to get dictionary of all options for items in config_items.items(): print(items) root.mainloop()
Output:('activeimage', ('activeimage', '', '', '', ''))
('anchor', ('anchor', '', '', 'center', 'center'))
('disabledimage', ('disabledimage', '', '', '', ''))
('image', ('image', '', '', '', 'pyimage1'))
('state', ('state', '', '', '', ''))
('tags', ('tags', '', '', '', ''))
image is one of the options you can configure. This code uses itemconfigure to change the image after the canvas image object is created.import tkinter as tk root = tk.Tk() canvas = tk.Canvas(root, height=100, width=100) canvas.pack() one = tk.PhotoImage(file='one.png') two = tk.PhotoImage(file='two.png') x = canvas.create_image(50, 50, image=one) # Create image object using image one canvas.itemconfigure(x, image=two) # Change image from one to two. root.mainloop()Other interesting options/atributes are "disabledimage" and "state". This code creates an image object that has a disabledimage. It uses the state option to toggle between the normal and disabled images.
import tkinter as tk root = tk.Tk() canvas = tk.Canvas(root, height=100, width=100) canvas.pack() def toggle(): if canvas.itemconfigure(x)['state'][4] == tk.DISABLED: canvas.itemconfigure(x, state=tk.NORMAL) else: canvas.itemconfigure(x, state=tk.DISABLED) canvas.after(1000, toggle) x = canvas.create_image(50, 50, image=tk.PhotoImage(file='one.png'), disabledimage=tk.PhotoImage(file='two.png')) toggle() root.mainloop()