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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/tkinter/python-tkinter-canvas-and-graphics-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics