将文本添加到画布中的矩形中?

问题描述 投票:0回答:1

如何在 Tkinter Canvas 中的矩形中创建文本?
因为,我所能做的就是创建 2 个独立的对象。
我尝试过这样做:

rect = canvas.create_rectangle(0,0,100,100,fill="orange")
text = canvas.create_text(50,50,text="Hello, Python!")

但那只是 2 个对象,我无法使用 1 行代码来移动它们。
那么,我该怎么做呢?

python tkinter canvas
1个回答
0
投票

最简单的解决方案是首先创建文本,然后根据文本的 bbox 创建矩形(这样您就不必猜测或硬编码坐标)。然后,确保两个对象具有相同的标签。然后,您可以使用标签将它们作为一个单元移动在一起。

import tkinter as tk

def fall(canvas, tag):
    canvas.move(tag, 0, 1)
    (x1,y1,x2,y2) = canvas.bbox(tag)
    if y1 < canvas.winfo_height():
        # continue to move until it is below the visible area of the canvas
        canvas.after(50, fall, canvas, tag)

root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack(fill="both", expand=True)

text = canvas.create_text(50, 50, text="Hello, Python!", tags=("boxed_text",))
rect = canvas.create_rectangle(canvas.bbox(text), fill="orange", tags=("boxed_text",))
canvas.lower(rect)

# wait for the window to be visible, then start moving the label
canvas.wait_visibility()
fall(canvas, "boxed_text")

tk.mainloop()

© www.soinside.com 2019 - 2024. All rights reserved.