user3636665
user3636665

Reputation: 21

Tkinter add stroke to text

I can't figure out how to add stroke to text with the create_text method.

There is no outline option defined in the method itself, does anyone know a method?

Thanks!

Upvotes: 2

Views: 2744

Answers (2)

Dr.Neo
Dr.Neo

Reputation: 136

I am so late to this party, but what works somewhat well is this: we place several texts in space with offset and the result looks convincing

def create_stroked_text(
        canvas,
        x,
        y,
        text,
        stroke_color,
        fill_color,
        stroke_width=1,
        anchor="ne",
        font_size=12,
    ):
        text_font = font.Font(family="Helvetica", size=font_size, weight="bold")

        # iterates in space in all directions and draws text
        # TODO better to iterate in a circle by angle here
        for dx in (-stroke_width, 0, stroke_width):
            for dy in (-stroke_width, 0, stroke_width):
                if dx != 0 or dy != 0:
                        canvas.create_text(
                        x + dx,
                        y + dy,
                        text=text,
                        font=text_font,
                        fill=stroke_color,
                        anchor=anchor,
                    )
        # place actual text here
        canvas.create_text(
            x, y, text=text, font=text_font, fill=fill_color, anchor=anchor
        )

Upvotes: 0

atlasologist
atlasologist

Reputation: 3974

AFAIK, there's no built-in way to add stroke to text, but you can configure your own. This kind of works by just making a bold-weighted text and overlaying regular text on it:

def stroke_text(x, y, text, textcolor, strokecolor):
    # make stroke text
    canvas.create_text(x, y, text=text, font=('courier', 16, 'bold'), fill=strokecolor)
    # make regular text
    canvas.create_text(x, y, text=text, font=('courier', 16), fill=textcolor)

root = Tk()

canvas = Canvas(root, bg='black')
canvas.pack()
stroke_text(100, 50, 'hello', 'white', 'red')

mainloop()

Although this probably looks more like a dropshadow than stroke; there's probably a way to improve this.

Upvotes: 4

Related Questions