【问题标题】:How to keep a Tkinter widget on top of the others如何将 Tkinter 小部件置于其他小部件之上
【发布时间】:2016-02-28 06:02:49
【问题描述】:

我有一些代码可以左右移动图像,但我不希望它们出现在右边框的顶部,我将其绘制为矩形。 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()

【问题讨论】:

  • 您是在寻找通用解决方案,还是特别想解决边界模糊的问题?简单的分层机制见stackoverflow.com/a/9576938/7432
  • tag_raise 对我有用。我现在知道类似的方法,例如提升/降低。你的帖子也很有趣,谢谢

标签: python-2.7 tkinter tkinter-canvas


【解决方案1】:

使用tag_raise()方法:

canvas.tag_raise(tile)

【讨论】:

  • 谢谢你,成功了。既然您建议了 tag_raise,我发现我的问题可能与这个问题重复:stackoverflow.com/questions/10959858/… 在我的真实案例中,我有更多的图像、前景和背景矩形,它们必须保持在彼此下方或上方。我定义了一些标签并在标签上调用了tag_raise,例如:canvas.tag_raise("ontop")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 2021-01-09
相关资源
最近更新 更多