如何将 Tkinter 小部件置于其他小部件之上

How to keep a Tkinter widget on top of the others

我有一些代码可以左右移动图像,但我不希望它们出现在右边框的顶部,我将其绘制为矩形。 Tkinter 中有哪些选项可以保留一个小部件(在我的示例中是一个矩形)在其他一些小部件之上(在我的代码中是一个图块,这是一个图像)? 我正在一个 canvas 上绘制矩形和图像。

我可以想象使用两个 canvas 可以解决问题,但是还有其他 options/settings 吗? 谢谢

import Tkinter as tk # for Python2
import PIL.Image, PIL.ImageTk

win = tk.Tk()
#Create a canvas
canvas = tk.Canvas(win, height = 500, width = 500)

#Create a rectangle on the right of the canvas
rect = canvas.create_rectangle(250, 0, 500, 250, width = 2, fill = "red")

#Create an image
SPRITE = PIL.Image.open("sprite.png")
tilePIL = SPRITE.resize((100, 100))
tilePI = PIL.ImageTk.PhotoImage(tilePIL)
tile = canvas.create_image(100, 100, image = tilePI, tags = "a tag")

#Place the canvas
canvas.grid(row = 1, column = 0, rowspan = 5)

#Move the tile to the right. 
#The tile will go on top of red rectangle. How to keep the rectangle on top of the tile?
canvas.coords(tile, (300, 100))
canvas.mainloop()

使用tag_raise()方法:

canvas.tag_raise(tile)