Tkinter Canvas widget can be used for many purposes such as adding images, creating and drawing shapes in the canvas, animating the shapes and objects, etc. Using the Canvas inbuilt functions and methods, we can create and display the text.
To create a text, we use create_text(x,y, text, **options) method. To add an outline around the text in Canvas, we have to create the bounding box around the text. The bounding box property links the invisible box with the widget. And, this will allow us to put a rectangle in the text.
Once we have created a rectangle, we can pull this behind and make the text above the rectangle. The rectangle must be given an outline property that surrounds the canvas item.
Example
# Import the required libraries from tkinter import * # Create an instance of tkinter frame or window win=Tk() # Set the size of the window win.geometry("700x350") # Create a canvas widget canvas=Canvas(win, bg="blue3") canvas.pack() # Create a text in canvas text=canvas.create_text(100,200, text="This works only in canvas", font=('Calibri 18'), anchor="w", fill="white") # Make the bounding-box around text bbox=canvas.bbox(text) # Create a rectangle inside the bounding box rect=canvas.create_rectangle(bbox, outline="yellow", fill="black", width=5) # Make the text above to the rectangle canvas.tag_raise(text,rect) win.mainloop()
Output
If we will run the above code, it will display a window with a predefined text in the canvas. The text would have an outline visible on the canvas.