tkinter
  1. tkinter-canvas

Canvas - Basic Tkinter Widgets

The Canvas widget in Tkinter allows for basic drawing and manipulation of 2D graphics. It provides a coordinate system that can be used to draw lines, shapes, and images on a window.

Syntax

canvas = Canvas(master, options)

Here, master represents the parent window or frame, and options are the configuration options for the canvas widget.

Example

The following example demonstrates how to create a canvas widget and draw a line and rectangle on it:

from tkinter import *
root = Tk()

canvas = Canvas(root, width=300, height=300)
canvas.pack()

line = canvas.create_line(0, 0, 300, 300)
rectangle = canvas.create_rectangle(50, 50, 250, 250)

root.mainloop()

Output

The above example will display a window with a canvas that contains a diagonal line from the top left corner to the bottom right corner and a rectangle in the center.

Explanation

The Canvas widget provides a coordinate system on which lines, shapes, and images can be drawn. In the above example, create_line() and create_rectangle() methods were used to draw a line and rectangle on the canvas, respectively. The coordinates for these shapes are given as arguments to these methods.

Use

The Canvas widget is useful when you want to create custom graphics or visualizations. It can be used for drawing charts, graphs, or diagrams. It is also useful for creating games or interactive user interfaces.

Important Points

  • The Canvas widget provides a coordinate system in which shapes can be drawn.
  • The create_line() and create_rectangle() methods are used to draw lines and rectangles, respectively.
  • The coordinate system of the Canvas widget starts from the top left corner of the widget and extends to the bottom right corner.

Summary

The Canvas widget in Tkinter provides a platform for basic drawing and manipulation of 2D graphics. It is useful for creating custom graphics and visualizations and can be used to draw lines, shapes, and images on a window. The create_line() and create_rectangle() methods are used to draw lines and rectangles, respectively, on the canvas widget.

Published on: