Tkinter – How to Put an Outline on a Canvas Text
Tkinter is a Python library that provides a way to create graphical user interfaces for Python applications. It includes a canvas widget, which is used to draw shapes, images, and text. In this article, we will explore how to put an outline on a canvas text using Tkinter.
Creating a Canvas
Before we can put an outline on a canvas text, we need to create a canvas first. The following sample code creates a canvas with a width and height of 400 pixels:
import tkinter as tk
# Create a window
root = tk.Tk()
# Create a canvas
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
# Run the main window loop
root.mainloop()
Adding Text to the Canvas
Once we have created a canvas, we can add text to it using the create_text
method. We can specify the text, the x and y coordinates where the text should appear, and other properties such as font, fill color, and anchor.
The following sample code adds the text “Hello, World!” to the center of the canvas:
# Add text to the canvas
text_id = canvas.create_text(200, 200, text="Hello, World!", font=("Helvetica", 24), fill="black", anchor="center")
Adding an Outline to the Text
To add an outline to the text, we can use the itemconfig
method to modify the properties of the text. We can specify the item ID of the text and set the outline
and width
properties to create an outline.
The following sample code adds a red outline with a width of 2 pixels to the text:
# Add an outline to the text
canvas.itemconfig(text_id, outline="red", width=2)
Complete Code
The complete code for putting an outline on a canvas text is as follows:
import tkinter as tk
# Create a window
root = tk.Tk()
# Create a canvas
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
# Add text to the canvas
text_id = canvas.create_text(200, 200, text="Hello, World!", font=("Helvetica", 24), fill="black", anchor="center")
# Add an outline to the text
canvas.itemconfig(text_id, outline="red", width=2)
# Run the main window loop
root.mainloop()
Conclusion
Tkinter provides a convenient way to create graphical user interfaces for Python applications. In this article, we have explored how to put an outline on a canvas text. By creating a canvas, adding text to it, and modifying the text properties, we can easily create text with an outline. With this knowledge, we can add visual interest and emphasis to our Python applications.