Tkinter – How to create colored lines based on length?


Tkinter Canvas widget is one of the versatile widgets which is generally used to draw shapes, arcs, objects, display images or any content. The objects inside the Canvas widget can be modified as well as configured using the configure() method or within the constructor by providing values to the properties.

To create lines on a Canvas widget, you can use the create_lines(x0,x1,x2,x3, fill="color", width, **options) constructor. In the constructor, you can assign the values of x0(top), x1(right), x2(bottom) and x3(left) which would decide the length of the lines to be drawn inside the canvas widget.


Let's take an example to understand how it works. In this example, we will create three lines with different colors in the Canvas widget.

# Import the tkinter library
from tkinter import *

# Create an instance of tkinter canvas by executing it
win = Tk()
win.title("Colored Lines")

# Create a canvas widget
my_canvas = Canvas(win, width=400, height=400, background="yellow")

# Create colored lines by providing length and width
my_canvas.create_line(20, 0, 400, 400, fill="#44a387", width=10)
my_canvas.create_line(0, 0, 400, 300, fill="#a5a344", width=10)
my_canvas.create_line(0, 0, 400, 200, fill="#9d44a3", width=10)

# Run the mainloop


Running the above code will display some colored lines in the Canvas widget.

Published on 22-Dec-2021 08:06:11