tkinter:是否可以用一条线连接 2 个框架?

tkinter: Is it possible to connect 2 frames with a line?

我正在尝试使用 tkinter 构建一个简单的 GUI。但是我 运行 遇到了问题。

我有 2 个 canvas,看到红色和绿色方块,在更大的 canvas 上。我想用一条线(蓝色)在视觉上将 2 canvas 相互连接起来。

我创建了 2 个(红色和绿色)canvasses,那些 canvasses 会四处移动。

但是编码蓝线时我卡住了。我想在移动的 2 个帧之间编写一条线。无论框架彼此相距多远,该线都必须始终连接。所以我想知道 tkinter 或 ttk 是否有可能做到这一点?

下面是我的想法的一个小插图。

canvas 没有提供连接对象的方法,但您可以通过简单地在两个对象之间画线来模拟它。如果矩形已填充,则可以从一个矩形的中心点到另一个矩形的中心点绘制一条线。然后您可以降低堆叠顺序中的线,这样矩形后面的线部分就不会显示。

如果你给直线一个可以计算的标签,只要其中一个矩形移动,你也可以重新计算连接它们的直线的坐标。

import tkinter as tk
import random

def connect(a,b):
    # compupte the tag, then delete any existing lines
    # between these two objects
    tag = f"connector_{a}_{b}"
    canvas.delete(tag)

    ax0, ay0, ax1, ay1 = canvas.coords(a)
    bx0, by0, bx1, by1 = canvas.coords(b)

    x0 = (ax0 + ax1) / 2
    y0 = (ay0 + ay1) / 2

    x1 = (bx0 + bx1) / 2
    y1 = (by0 + by1) / 2

    # create the line, then lower it below all other
    # objects
    line_id = canvas.create_line(x0, y0, x1, y1, fill="blue", width=4, tags=(tag,))
    canvas.tag_lower(line_id)

def move_rectangles():
    canvas.move(f1, random.randint(-50, 50), 0)
    canvas.move(f2, 0, random.randint(-50, 50))
    connect(f1, f2)

root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=500, background="white")
button = tk.Button(root, text="Move rectangles", command=move_rectangles)

button.pack(side="top")
canvas.pack(side="top", fill="both", expand=True)

f1 = canvas.create_rectangle(50,50, 150, 250, outline="red", fill="white", width=4)
f2 = canvas.create_rectangle(250,100, 350, 350, outline="green", fill="white", width=4)

connect(f1, f2)


root.mainloop()