Home > OS >  How to draw a line in Tkinter with n segments?
How to draw a line in Tkinter with n segments?

Time:10-12

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?

CodePudding user response:

there is an option in canvas.create_line called dash .For exemple :

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

CodePudding user response:

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 - gap/2

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

    _x, _y = x, y # initial positions
    for s in range(number_of_seg): 

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

    canvas.moveto("segline", x, y) # reposition to x, y moveto() available in python >=3.8


root = tk.Tk()

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

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

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

root.mainloop()
  • Related