The Canvas widget in Tkinter is used to create and manage structured graphics in Python applications. You can use the Canvas widget to draw shapes, lines, and even plots in your window. It's highly customizable and can be used to implement complex graphical elements.
w = Canvas(parent, options)
Here, parent refers to the parent widget (usually the main application window), and options are various settings used to configure the canvas.
| SN | Option | Description |
|---|---|---|
| 1 | bd | Specifies the border width of the canvas. Default value is 2 pixels. |
| 2 | bg | Specifies the background color of the canvas. |
| 3 | confine | Ensures that the canvas cannot be scrolled outside of its scroll region when set to True. |
| 4 | cursor | Sets the cursor style on the canvas (e.g., arrow, circle, dot). |
| 5 | height | Sets the height of the canvas in the vertical direction (pixels). |
| 6 | highlightcolor | Specifies the color used when the widget is focused. |
| 7 | relief | Sets the type of the canvas border (SUNKEN, RAISED, GROOVE, RIDGE). |
| 8 | scrollregion | Defines the scrollable region of the canvas as a tuple of coordinates (x1, y1, x2, y2). |
| 9 | width | Specifies the width of the canvas in the horizontal direction (pixels). |
| 10 | xscrollincrement | If set to a positive value, the canvas moves horizontally in increments of this value. |
| 11 | xscrollcommand | Binds the canvas to the .set() method of the horizontal scrollbar. |
| 12 | yscrollincrement | Similar to xscrollincrement, but for vertical movement. |
| 13 | yscrollcommand | Binds the canvas to the .set() method of the vertical scrollbar. |
from tkinter import *
# Create the main window
root = Tk()
# Create a canvas widget
canvas = Canvas(root, bg="lightgray", height=400, width=400)
# Draw a line
canvas.create_line(50, 50, 300, 300, fill="blue", width=3)
# Draw a rectangle
canvas.create_rectangle(100, 100, 200, 200, fill="red")
# Draw an oval (similar to a circle)
canvas.create_oval(150, 150, 250, 250, outline="green", width=2)
# Display the canvas
canvas.pack()
# Run the application
root.mainloop()
• Canvas creation: A canvas of size 400x400 pixels with a light gray background is created.
• Line: A blue line is drawn from the coordinates (50, 50) to (300, 300).
• Rectangle: A red rectangle is drawn from coordinates (100, 100) to (200, 200).
• Oval: An oval (circle) is drawn within the bounding box defined by (150, 150) and (250, 250).
The Canvas widget provides methods like create_line(), create_rectangle(), and create_oval() to draw shapes. You can also create other graphical elements like polygons, arcs, and text, making it a powerful tool for graphical applications in Tkinter.