Home > front end >  Placing Other Tkinter Objects in Front of Label Objects
Placing Other Tkinter Objects in Front of Label Objects

Time:07-08

I'm new here, so forgive any glaring stackoverflow convention issues. I am working with tkinter, and I have placed images across my canvas using label objects. Now I would like to place other canvas objects (for instance, ovals) on top of the images, but I'm finding that the images always block the ovals. I have tried commands like tag_raise, but all to no avail. Is there some way I can get canvas objects to not be blocked by images? By the way, I need my images to be placed in specific locations and to have specific heights and widths. Also, I'm new to tkinter, so I would appreciate detail. Thanks in advance!

CodePudding user response:

The canvas documentation explicitly states that you cannot draw above embedded widgets:

"Note: due to restrictions in the ways that windows are managed, it is not possible to draw other graphical items (such as lines and images) on top of window items. A window item always obscures any graphics that overlap it, regardless of their order in the display list."

You can, however, add images to a canvas without using a Label widget. The canvas has a create_image method which can be used to add images directly to the canvas. When images are added in this way, other canvas items can be added on top.

import tkinter as tk

root = tk.Tk()
image = tk.PhotoImage(file="/tmp/image.png")
cx = image.width()//2
cy = image.height()//2

canvas = tk.Canvas(root, bg="black", bd=0, highlightthickness=0,
                   width=image.width(), height=image.height())
canvas.pack(fill="both", expand=True)

canvas.create_image(cx, cy, image=image)
canvas.create_oval(cx-20, cy-20, cx 20, cy 20, fill="red")

root.mainloop()

screenshot, image overlaid with oval

  • Related