Search code examples
pythontkintercanvasdrawingtkinter-canvas

Draw a THICK curve on a tkinter Canvas


I want to use the tkinter Canvas object to draw handwriting on the screen. Using the example code from the tkdocs website, I get the following drawing artifacts when I use a large line width of say 20:

enter image description here

However, for small line widths, everything's fine:

enter image description here

Here's the complete Python code:

from tkinter import *
from tkinter import ttk

class Sketchpad(Canvas):
    def __init__(self, parent, **kwargs):
        super().__init__(parent, **kwargs)
        self.bind("<Button-1>", self.save_posn)
        self.bind("<B1-Motion>", self.add_line)
        
    def save_posn(self, event):
        self.lastx, self.lasty = event.x, event.y

    def add_line(self, event):
        self.create_line((self.lastx, self.lasty, event.x, event.y))
        self.save_posn(event)

root = Tk()
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

sketch = Sketchpad(root)
sketch.grid(column=0, row=0, sticky=(N, W, E, S))

root.mainloop()

I'm using Python 3.8.

What I tried so far:

  • different joinstyles have no effect
  • the smooth argument has no effect
  • various unsuccessful dirty hacks and workarounds not worth to mention

Anybody an idea how I can get rid of the artifact?

Thanks!


Solution

  • You can use capstyle='round' in create_line():

    self.create_line((self.lastx, self.lasty, event.x, event.y), width=20, capstyle='round')