Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to colorize the outline of a canvas rectangle in Tkinter?
In Tkinter, you can colorize the outline of a canvas rectangle using the outline parameter in the create_rectangle() method. This allows you to create visually appealing rectangles with colored borders.
Syntax
canvas.create_rectangle(x1, y1, x2, y2, outline='color', width=thickness, fill='fill_color')
Parameters
The key parameters for rectangle outline customization are:
- outline − Color of the rectangle border (e.g., 'red', '#FF0000')
- width − Thickness of the outline in pixels
- fill − Interior color of the rectangle (optional)
Example
In this example, we will create a rectangle on a Tkinter canvas and apply a yellow outline with green fill ?
# Import the required libraries
from tkinter import *
# Create an instance of Tkinter Frame
win = Tk()
# Set the geometry
win.geometry("700x350")
# Define a Canvas Widget
canvas = Canvas(win, width=500, height=350)
canvas.pack()
# Create a rectangle in Canvas with colored outline
canvas.create_rectangle(100, 100, 300, 300, outline='yellow', width=4, fill='green')
win.mainloop()
Multiple Rectangles with Different Outlines
You can create multiple rectangles with different outline colors and styles ?
from tkinter import *
win = Tk()
win.geometry("700x400")
canvas = Canvas(win, width=600, height=400, bg='white')
canvas.pack()
# Rectangle with red outline
canvas.create_rectangle(50, 50, 150, 150, outline='red', width=3, fill='lightblue')
# Rectangle with blue outline
canvas.create_rectangle(200, 50, 300, 150, outline='blue', width=5, fill='lightyellow')
# Rectangle with green outline (no fill)
canvas.create_rectangle(350, 50, 450, 150, outline='green', width=2)
# Rectangle with purple outline using hex color
canvas.create_rectangle(125, 200, 275, 300, outline='#8A2BE2', width=6, fill='pink')
win.mainloop()
Key Points
- Use the
outlineparameter to set border color - The
widthparameter controls outline thickness - Colors can be specified as names ('red') or hex codes ('#FF0000')
- Omitting
fillcreates a transparent interior - Setting
outline=''removes the border entirely
Conclusion
Use the outline parameter in create_rectangle() to add colored borders to canvas rectangles. Combine with width and fill parameters for complete visual customization.
Advertisements
