How to put an outline on a canvas text on python — tkinter?

Question:

I’ve created a white text in the center of my canvas, but my background is very colorful and one part of it is a very light color, so some corners of my sentence doesn’t appear. I can’t find any options to set borders or an outline. what could I do?

Asked By: Ch.Lama

||

Answers:

Create a text item, get the bounding box of that item, use that data to create a rectangle, and raise the text above the rectangle.

import Tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root, background="white")
canvas.pack(fill="both", expand=True)

text_item = canvas.create_text(20, 20, anchor="w", text="Hello world!", fill="white")
bbox = canvas.bbox(text_item)
rect_item = canvas.create_rectangle(bbox, outline="red", fill="black")
canvas.tag_raise(text_item,rect_item)

root.mainloop()
Answered By: Bryan Oakley

You can place different colour text on top, just move it several pixels

text_bg = canvas.create_text(400, 100, text="Hello World!", font=("Helvetica", 40), fill='white')
text_fg = canvas.create_text(402, 102, text="Hello World!", font=("Helvetica", 40), fill='black')