0

I have the following code for drawing on canvas and then saving my drawings as images:

def paint(event):
    global brush_size
    global color
    x1 = event.x - brush_size
    x2 = event.x + brush_size
    y1 = event.y - brush_size
    y2 = event.y + brush_size
    w.create_oval(x1, y1, x2, y2,
                  fill = color,
                  outline=color)


def getter(widget):
    x = root.winfo_rootx() + widget.winfo_x()
    y = root.winfo_rooty() + widget.winfo_y()
    x1 = x + widget.winfo_width()
    y1 = y + widget.winfo_height()
    ImageGrab.grab().crop((x,y,x1,y1)).save("img1.jpg")

root = Tk()
root.title("Paint")

w = Canvas(root,
           width=canvas_width,
           height=canvas_height,
           bg="white")
w.bind("<B1-Motion>", paint)

save_btn = Button(text="Save", width=10, command=getter(w))

w.grid(row=2, column=0,
       columnspan=7,
       padx=5, pady=5,
       sticky=E+W+S+N)

w.columnconfigure(6, weight=1)
w.rowconfigure(2, weight=1)

save_btn.grid(row=0, column=1)

root.mainloop()

But when I click 'save' button I get an empty 1x1px jpg file. Could you please tell me what's wrong with that?

P.S. and some additional question. When I'm drawing fast I don't get a continuous line. I get dots with gaps between instead. How do I fix this?

Igor234
  • 359
  • 1
  • 3
  • 11

1 Answers1

2

I'm not entirely sure how tkinter works so this is just a guess, but it looks like you are binding the result of getter(w) (None), instead of the function. You could solve this like lambda: getter(w). And for your additional question, you could record previous mouse positions and draw a line between the current and previous positions. You could also define a function specifically to save the image, and use that as the command.

internet_user
  • 3,149
  • 1
  • 20
  • 29
  • I have verified that you are indeed correct and your suggestion works (if all the stuff missing the question's code added first to make it runnable). – martineau Nov 10 '17 at 21:59
  • For additional question. I took the drawing part of code from qt tutorial on youtube. And the guy on the video draws continuous lines using the same code. Why can't I? – Igor234 Nov 11 '17 at 08:48