You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Tkinter中绘制带有n个分段的直线?

你可以通过均分两点间坐标、间隔绘制线段的方式实现指定数量的分段直线,参考实现如下:

def connect_nodes(node, node_to_connect, segments, color, canvas, gap_ratio=0.2):
    # gap_ratio 为分段间隙占单段总长度的比例,可按需调整
    dx = node_to_connect[0] - node[0]
    dy = node_to_connect[1] - node[1]
    # 计算每段(含间隙)的横向、纵向步长
    step_x = dx / segments
    step_y = dy / segments
    # 单段实际绘制的长度占比
    draw_ratio = 1 - gap_ratio
    for i in range(segments):
        # 计算当前段的起点
        start_x = node[0] + i * step_x
        start_y = node[1] + i * step_y
        # 计算当前段的终点(跳过间隙部分)
        end_x = start_x + step_x * draw_ratio
        end_y = start_y + step_y * draw_ratio
        canvas.create_line(start_x, start_y, end_x, end_y, fill=color)
  • 上述代码默认间隙占单段总长度的20%,你可以调整gap_ratio参数修改间隙大小,设置为0时就是无间隙的普通直线
  • 如果需要固定像素大小的间隙,可以根据两点总距离动态计算gap_ratio,无需修改核心逻辑

内容的提问来源于stack exchange,提问作者CairoMisr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 22:45:03