How to draw a line in Tkinter with n segments?

Viewed 346

I'd like to draw lines with an n number or segments as such (this is a line with 5 segments).

Here is what I have:

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)

This draws a straight line without any segments. Is there a way to segment the line such that it has segments number of segments?

2 Answers

Using dash=(pixels_to_draw, gap_in_pix)(eg: dash=(5, 1)) option of create_line will not give you control over how many segments a line could be broken into.

If you want to break a line into specified segments, you will have to draw multiple lines, and if you want to modify the line give it the same tag.

Here is an example.

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

There is an option in canvas.create_line called dash. For example :

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