- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Tkinter – How to create colored lines based on length?
Tkinter Canvas widget is one of the versatile widgets which is generally used to draw shapes, arcs, objects, display images or any content. The objects inside the Canvas widget can be modified as well as configured using the configure() method or within the constructor by providing values to the properties.
To create lines on a Canvas widget, you can use the create_lines(x0,x1,x2,x3, fill="color", width, **options) constructor. In the constructor, you can assign the values of x0(top), x1(right), x2(bottom) and x3(left) which would decide the length of the lines to be drawn inside the canvas widget.
Example
Let's take an example to understand how it works. In this example, we will create three lines with different colors in the Canvas widget.
# Import the tkinter library from tkinter import * # Create an instance of tkinter canvas by executing it win = Tk() win.geometry("700x350") win.title("Colored Lines") # Create a canvas widget my_canvas = Canvas(win, width=400, height=400, background="yellow") my_canvas.pack() # Create colored lines by providing length and width my_canvas.create_line(20, 0, 400, 400, fill="#44a387", width=10) my_canvas.create_line(0, 0, 400, 300, fill="#a5a344", width=10) my_canvas.create_line(0, 0, 400, 200, fill="#9d44a3", width=10) # Run the mainloop win.mainloop()
Output
Running the above code will display some colored lines in the Canvas widget.