简体   繁体   English

在前景中显示图像(tkinter)

[英]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. 我正在Tkinter(Python 3.7)中创建一个仪表板,并一直试图将图像放置在其他小部件之上以增强其外观。 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. 我一直在使用place()来定位我的小部件,因为我从不希望小部件移动,而只需要它在特定的屏幕分辨率下工作即可。 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. 到目前为止,我已经尝试过使用PIL包,并尝试将图像放置在标签和画布中,但是两者似乎具有相同的结果。 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. 当tkinter小部件重叠时,tkinter将使用堆叠顺序 (有时称为z-index)来确定哪个小部件覆盖另一个。

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. 您可以使用lowerlift方法更改此顺序。 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. 您也可以按原样保留代码,并在代码结尾附近添加label.lift() ,以将其提升到堆叠顺序的顶部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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