Tkinter Canvas Text

Muhammad Maisam Abbas Oct 29, 2021
Tkinter Canvas Text

This tutorial will introduce how to write text to our Tkinter canvas.

Write Text to Tkinter Canvas With the create_text() Function

The Tkinter package is the standard GUI programming library in Python. The Canvas is a rectangular area used for writing and drawing in the Tkinter package. To write any text in our Tkinter Canvas, we first have to install the Tkinter package with the following pip command.

pip install tk

The create_text(x, y, font, text,...) function can be used to write text to our Tkinter Canvas. The create_text() function takes many parameters, but we are only interested in the first 4 parameters for now. The first 2 parameters, x and y, are the coordinates. The following parameter, font, is the font of the text, and the fourth parameter, text, is the actual text.

We can use the create_text() function by creating and initializing an object of the Canvas class. The constructor of the Canvas class Canvas(frame, width, height, bg) also takes 4 parameters. The first parameter, frame, is the actual frame itself. The following two parameters, width and height, are the canvas’ width and height, respectively, and the fourth parameter bg is the background color of the canvas.

The frame is nothing but an object of the Tk class. The following code shows us how to write text to our Tkinter Canvas with the create_text() function.

from tkinter import *

frame = Tk()

frame.geometry("320x320")

canvas = Canvas(frame, width=320, height=320, bg="SpringGreen2")

canvas.create_text(100, 100, text="Some Text", fill="black", font=("Helvetica 15 bold"))

canvas.pack()
frame.mainloop()

Output:

add text to tkinter canvas

We first imported everything in the Tkinter library and created an instance of the Tk class named frame. We then define the dimensions of our frame with frame.geometry("320x320"). After that, we created our canvas by passing this frame to the constructor of the Canvas class. In the end, we write our text with the canvas.create_text() function and pack our widget inside the frame with canvas.pack().

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn