如何在 Tkinter 中用 n 段画一条线?

How to draw a line in Tkinter with n segments?

我想用 n 个数字或线段画线 as such(这是一条有 5 线段的线)。

这是我的资料:

def connect_nodes(node, node_to_connect, segments, color, canvas):
    canvas.create_line(node[0], node[1], node_to_connect[0], node_to_connect[1], fill=color)

这会绘制一条没有任何线段的直线。有没有办法分割线,使其具有 segments 个线段?

canvas.create_line 中有一个名为 dash 的选项。例如:

import tkinter
root = tkinter.Tk()
f = tkinter.Canvas(root,height = 200,width = 200)

f.create_line(0,0,200,200,dash=10)
f.pack()
root.mainloop()

使用 dash=(pixels_to_draw, gap_in_pix)(例如:dash=(5, 1))选项 create_line 将无法让您控制一条线可以分成多少段。

如果你想把一条线分成指定的段,你将不得不画多条线,如果你想修改线给它相同的标签。

这是一个例子。

import tkinter as tk
import math


def create_segmented_line(x, y, x1, y1, number_of_seg: int, gap: int, *args, **kwargs):

    line_length = math.sqrt((x1 - x)**2 + (y1 - y)**2)

    seg = line_length / number_of_seg 

    n_x, n_y = (x1-x) / line_length, (y1-y) / line_length

    _x, _y = x, y
    dist = seg - gap/2
  
    tag = f"segment{id(seg)}" # keep tag unique for each segment

    for s in range(number_of_seg): 

        canvas.create_line(_x, _y, ((dist - gap/2)*n_x) + x, ((dist - gap/2)*n_y) + y, tags=tag, *args, **kwargs)
        _x, _y = ((dist + gap/2)*n_x) + x, ((dist + gap/2)*n_y) + y
        dist += seg

    return tag

root = tk.Tk()

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

x, y, x1, y1 = 50, 100, 150, 150

create_segmented_line(x, y, x1, y1, 5, 2)

root.mainloop()