CANVAS IN TKINTER
In this tutorial, we are going to learn about the canvas in Tkinter and what we can do with it followed by a handy example
Recommended Book: Python GUI Programming with Tkinter
What is Canvas in Tkinter ?
The canvas widget is used to add graphics in the python application. We can draw different graphics and shapes. You can easily declare canvas and later add different features to it.
canvas_tk = Canvas( window, features)
Discover how to create visually stunning and feature-rich applications by using Python’s built-in Tkinter GUI toolkit
Canvas features and properties are:
1 | bd | bd displays the border width |
2 | bg | bg displays the background color of the canvas
It represents the background color of the canvas. |
3 | confine | This property doesn’t let you scroll outside the scroll region. |
4 | cursor | You can use the cursor as different shapes on the screen as circle, dot etc. |
5 | height | Displays the size of the canvas as in the Y dimension. |
6 | highlightcolor | Displays the highlighted color in focus |
7 | relief | This displays different types of borders like SUNKEN, RAISED, GROOVE, and RIDGE. |
8 | scrollregion | Allows how much the area can be scrolledin TOP, RIGHT, LEFT and BOTTOM poistions. |
9 | width | Sets the width of the canvas |
10 | xscrollincrement | If the value of set to a positive value then the canvas will only be placed to the multiple of that value horizontally |
11 | xscrollcommand | If you have a scrollable canvas, then xscrollcommand will be used as a .set() method for the horizontal scrollbar |
12 | yscrollincrement | If the value of set to a positive value then the canvas will only be placed to the multiple of that value vertically |
13 | yscrollcommand | If you have a scrollable canvas, then yscrollcommand will be used as a .set() method for the vertical scrollbar |
Creating Your First Canvas in Tkinter
import tkinter as tk screen = tk.Tk() #Screen size screen.geometry('300x300') #Drawing your canvas canvas_tk = tk.Canvas(screen, bg='yellow', width=250, height=250) canvas_tk.pack() screen.mainloop()
Output:
Coordinates in Canvas
We use pixels on canvas in terms of using x,y coordinates. But there is a slight difference between using coordinates in canvas tkinter and using coordinates in plain geometry. The y axis goes down in positive number instead of going up which makes the left corner of the canvas to be the starting point.
Creating an Oval on Your Canvas
We are going to create an oval where (50,50,100,100) is going to be our coordinates (50,50) being the starting point and 100,100 being the ending point of the shape.
oval = canvas_tk.create_oval(50,50,100,100, fill='red')
Output:
You can create different shapes on your canvas like arc and lines by using coordinates.