Tkinter Canvas
Tkinter Canvas widget
In this tutorial, you shall learn about Canvas widget in TKinter: What is a Canvas widget, how to create a Canvas widget, and an example for Canvas widget.
What is Canvas widget in Tkinter
The Canvas widget is one of the available components in Tkinter that allows you to draw and manipulate graphics, such as lines, shapes, text, and images, on a rectangular area.
The following is a screenshot of the Canvas widget with circle and rectangle drawn it the canvas.
How to create a Canvas widget in Tkinter?
To create a Canvas widget in Tkinter, you can use the Canvas class constructor. The parent window must be passed as the first argument, and this is the mandatory parameter. Rest of the parameters are optional and can be passed as keyword arguments, or you can set these options after initializing the Canvas widget object.
A simple example to create a Canvas widget is given below.
import tkinter as tk
window = tk.Tk()
canvas = tk.Canvas(window)
You can also pass keyword arguments like width, height, etc..
canvas = tk.Canvas(window, width=400, height=400)
- window specifies the parent for this Canvas widget.
- width specifies the number of pixels along the horizontal axis.
- height specifies the number of pixels along the vertical axis.
Example for Canvas widget in Tkinter
In this example, we shall create a simple GUI application using Tkinter with a Canvas widget, and draw a circle in this Canvas using Canvas.create_oval() method.
Python Program
import tkinter as tk
# Create the main window
window = tk.Tk()
window.geometry("500x500")
window.title("PythonExamples.org")
# Create a Canvas widget
canvas = tk.Canvas(window, width=400, height=400)
canvas.pack()
# Draw an oval on the canvas
canvas.create_oval(100, 100, 300, 300, fill='green')
window.mainloop()
Output in MacOS
Summary
In this Python Tkinter tutorial, we have seen what a Canvas widget is, how to create a Canvas widget, and an example for Canvas with a circle in it.