Tkinter Canvas – Create Line

Tkinter Canvas – Create Line

In Tkinter, you can create a line on Canvas widget from a specific (x1, y1) coordinate to a specific (x2, y2) coordinate.

Tkinter Canvas - Create Line

To create a line on a Tkinter Canvas widget, you can use the create_line() method of the Canvas class. This method takes the coordinates of two points as arguments and returns an identifier for the created line object on the canvas. The first point (x1, y1) defines the starting of our line. The second point (x2, y2) defines the ending of our line.

To create or draw a line from (x1, y1) coordinate to (x2, y2) coordinate on the Canvas, use the following syntax.

Canvas.create_line(x1, y1, x2, y2)

We can also specify other options to the method like fill color, width of the line, etc.

In this tutorial, you shall learn how to create a line on the Canvas widget in Tkinter, with examples.

Examples

1. Create line from (10, 10) to (200,150) on Canvas

In this example, we shall create a Canvas canvas_1, and create a line on this Canvas from (10, 10) to (200,150).

Python Program

import tkinter as tk

# Create the main window
window = tk.Tk()
window.geometry("300x200")
window.title("PythonExamples.org")

# Create a Canvas widget
canvas_1 = tk.Canvas(window, width=300, height=200)
canvas_1.pack()

# Create a line on the canvas
line_1 = canvas_1.create_line(10, 10, 200, 150)

window.mainloop()
Copy

Output in MacOS

Tkinter - Create line on Canvas
Create line on Canvas

2. Create line on Canvas, with specific fill color, and width

In this example, we shall create a line on Canvas, with a fill color of red, and width of 10.

Python Program

import tkinter as tk

# Create the main window
window = tk.Tk()
window.geometry("300x200")
window.title("PythonExamples.org")

# Create a Canvas widget
canvas_1 = tk.Canvas(window, width=300, height=200)
canvas_1.pack()

# Create a line on the canvas
line_1 = canvas_1.create_line(10, 10, 200, 150, fill='red', width=10)

window.mainloop()
Copy

Output in MacOS

Tkinter - Create line on Canvas with fill color red and width 10
Line on Canvas – Fill color red, and width 10

Summary

In this Python Tkinter tutorial, we have seen how to create a line on Canvas widget in Tkinter, with examples.

Related Tutorials

Code copied to clipboard successfully 👍