To draw a dashed line on a Tkinter canvas, we can use the dash parameter of create_line() method.
Steps −
Import the tkinter library and create an instance of tkinter frame.
Set the size of the frame using geometry method.
Create a Canvas widget and set its height and width.
Next, use the create_line function and pass the coordinates of the line (x1, y1) and (x2, y2).
To get a dashed line, use the dash parameter dash=(5,1) for 5px dash followed by 1px space.
You can set the color and width of the dashed lines using the fill and width parameters.
Finally, run the mainloop of the application window.
Example
# Import the library from tkinter import * # Create an instance of window win = Tk() # Set the geometry of the window win.geometry("700x350") C1 = Canvas(win, width=600, height=400) # Coordinates of the line coordinates = 100,150,550,150 # Draw a dashed vertical line, 5px dash and 1px space C1.create_line(coordinates, dash=(5,1)) C1.pack() win.mainloop()
Output
It will produce the following output −
Note: Dash patterns are system-dependent. You may get different outputs on Windows and Linux based systems. Windows doesn't support the same dash patterns as Linux.