简体   繁体   中英

Display image in foreground (tkinter)

I'm creating an instrument panel in Tkinter (Python 3.7) and have been attempting to place an image on top of other widgets to augment their appearance. The problem is, every time I place an image it ends up in the background. Ideally I would like to put an image with transparency over all the widgets in my panel, but I would settle for simply being able to put non-transparent images over parts of my display. I've been using place() to position my widgets since I never want the widgets to move and only need it to work for a specific screen resolution. So far I've tried using the PIL package and tried placing the image inside a label and a canvas, but both seem to have the same result. Even if I place my widgets inside the canvas with the image, the widgets will show up in front. Here's a simple example:

import tkinter as tk
import PIL.Image
import PIL.ImageTk

root = tk.Tk()
image = PIL.Image.open('esis/decals_green.gif')
photo = PIL.ImageTk.PhotoImage(image)
label = tk.Label(root, image=photo)
label.image = photo #keep reference

sampleWidget = tk.Button(root, text='Test')

sampleWidget.place(x=0, y=0, height=100, width=100)
label.place(x=0, y=0, height=200, width=200)

root.mainloop()

Even though I'm placing the image label last, it shows up underneath the button.

When tkinter widgets overlap, tkinter will use the stacking order (sometimes referred to as a z-index) to determine which widget overlays the other.

The stacking order defaults to the order in which the widgets are created (widgets created earlier are lower in the order than widgets created later). You can change this ordering with the lower and lift methods. Because you created the button widget last, it will have a higher place in the stacking order and thus it will appear on top of the image.

If you wait to create the label with the image until after all of the other widgets have been created, it will be highest in the stacking order and thus appear on top of all other widgets. You could also leave the code as-is and add label.lift() near the end of the code to raise it to the top of the stacking order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM