Python - GUI Programming - Canvas Widget

Python provides various GUI frameworks and one of the most commonly used is Tkinter. Tkinter provides a set of widgets for building graphical user interfaces. The Canvas widget is one of the most versatile widgets in Tkinter. It can be used to create various shapes, including rectangles, ovals, arcs, and polygons. It also allows you to add text and images to your GUI.

Creating a Canvas Widget

Before we start drawing shapes, we need to create a Canvas widget. Here's how:

import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
root.mainloop()

In the code above, we first import the tkinter module and create a Tk object. We then create a Canvas widget with a width of 400 pixels and a height of 400 pixels. Finally, we use the pack method to add the widget to the window and start the main event loop.

Drawing Shapes

Now that we have created a Canvas widget, let's start drawing shapes on it. The Canvas widget provides several methods for drawing different shapes, such as create_rectangle, create_oval, create_arc, and create_polygon. Here's an example:

import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
canvas.create_rectangle(50, 50, 150, 150, fill='red')
root.mainloop()

In the code above, we use the create_rectangle method to draw a red rectangle on the Canvas widget. The rectangle starts at the point (50, 50) and extends to the point (150, 150).

Let's draw some more shapes. Here's an example that draws an oval and an arc:

import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
canvas.create_oval(50, 50, 150, 100, fill='blue')
canvas.create_arc(50, 150, 150, 250, start=0, extent=180, fill='green')
root.mainloop()

In the code above, we use the create_oval method to draw a blue oval and the create_arc method to draw a green arc. The oval starts at the point (50, 50) and extends to the point (150, 100). The arc starts at the point (50, 150), has a width and height of 100 pixels, starts at 0 degrees, and extends 180 degrees.

Adding Text and Images

In addition to shapes, we can also add text and images to our Canvas widget. Here's an example that adds some text and an image:

import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
canvas.create_text(200, 50, text='Hello, World!', font=('Arial', 20))
photo = tk.PhotoImage(file='image.gif')
canvas.create_image(200, 200, image=photo)
root.mainloop()

In the code above, we use the create_text method to add the text "Hello, World!" to the Canvas widget. We also specify the font to use for the text.

We also use the create_image method to add an image to the Canvas widget. We first create a PhotoImage object using the tk.PhotoImage constructor