Creating a Blue rectangle on a Tkinter canvas widget
Python Tkinter Canvas and Graphics: Exercise-1 with Solution
Write a Python program to create a Tkinter window with a canvas widget that displays a blue rectangle.
Sample Solution:
Python Code:
import tkinter as tk
# Create the main Tkinter window
root = tk.Tk()
root.title("Blue Rectangle")
# Create a Canvas widget
canvas = tk.Canvas(root, width=300, height=200, bg="white")
canvas.pack()
# Draw a blue rectangle on the Canvas
rectangle = canvas.create_rectangle(50, 50, 250, 150, fill="blue")
# Start the Tkinter event loop
root.mainloop()
Explanation:
In the exercise above -
- Import "tkinter" as "tk" for creating GUI components.
- Create the main Tkinter window using tk.Tk() and set its title to "Blue Rectangle."
- Create a Canvas widget using tk.Canvas(), specifying its width, height, and background color.
- Draw a blue rectangle on the "Canvas" using the "canvas.create_rectangle()" method. The coordinates (50, 50) and (250, 150) specify the top-left and bottom-right corners of the rectangle, and fill="blue" sets the fill color to blue.
- The main event loop, root.mainloop(), starts the Tkinter application.
Output:
Flowchart:

Python Code Editor:
Previous: Python Tkinter Canvas and Graphics Home.
Next: Building a paint application with Python and Tkinter.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Summing a sequence of numbers (calculating the sum of zero to ten with skips):
>>> l = range(0,10,2) >>> sum(l) 20
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook