Py学习  »  Python

python tkinter可以用一条线连接两个帧吗

Ultiseeker • 3 年前 • 1363 次点击  

使用tkinter,我试图构建一个简单的GUI。但我遇到了一个问题。

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

我创建了两张(红色和绿色)画布,这些画布会四处移动。

但我在给蓝线编码时被卡住了。我想在两个移动的帧之间编码一行。无论相距多远,线路都必须始终连接。所以我想知道这在tkinter或ttk中是否可能?

下面是我脑海中的一个小幻觉。

Small illustation

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128609
 
1363 次点击  
文章 [ 1 ]  |  最新文章 3 年前
Bryan Oakley
Reply   •   1 楼
Bryan Oakley    3 年前

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

如果你给这条线一个可以计算的标记,每当其中一个矩形移动时,你也可以重新计算连接它们的线的坐标。

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

screenshot