如何将Tkinter小部件保留在其他小部件之上

时间:2016-02-28 06:02:49

标签: python-2.7 tkinter tkinter-canvas

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

我可以想象使用两个画布可以做到这一点,但有没有其他选项/设置? 感谢

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()

enter image description here

1 个答案:

答案 0 :(得分:1)

使用tag_raise()方法:

canvas.tag_raise(tile)