Trying to create a simple paint application, and i have a button which when pressed i expect to clear the canvas so a new drawing can be started.
I have buttons being rendered in the tkinter interface, and i have added the drawing_area.delete('all')
equivalent of canvas.delete('all')
command to my button, but when i draw on the canvas and click the button nothing appears to happen.
Not really sure where i'm going wrong here, would be awesome if someone could help me out, i've put the code for the application below.
from tkinter import *
import tkinter.font
from PIL import Image, ImageTk
class PaintApp:
# Stores current drawing tool used
drawing_tool = "pencil"
# Tracks whether left mouse is down
left_but = "up"
# x and y positions for drawing with pencil
x_pos, y_pos = None, None
# ---------- CATCH MOUSE UP ----------
def left_but_down(self, event=None):
self.left_but = "down"
# Set x & y when mouse is clicked
self.x1_line_pt = event.x
self.y1_line_pt = event.y
# ---------- CATCH MOUSE UP ----------
def left_but_up(self, event=None):
self.left_but = "up"
# Reset the line
self.x_pos = None
self.y_pos = None
# Set x & y when mouse is released
self.x2_line_pt = event.x
self.y2_line_pt = event.y
# ---------- CATCH MOUSE MOVEMENT ----------
def motion(self, event=None):
if self.drawing_tool == "pencil":
self.pencil_draw(event)
# ---------- DRAW PENCIL ----------
def pencil_draw(self, event=None):
if self.left_but == "down":
# Make sure x and y have a value
if self.x_pos is not None and self.y_pos is not None:
event.widget.create_line(self.x_pos, self.y_pos, event.x, event.y, smooth=TRUE)
self.x_pos = event.x
self.y_pos = event.y
def __init__(self, root):
# Add buttons for Finishing and Getting a new Word combo
drawing_area = Canvas(root, bd=2, highlightthickness=1, relief='ridge')
drawing_area.pack(side = LEFT, fill="both", expand=True)
drawing_area.bind("<Motion>", self.motion)
drawing_area.bind("<ButtonPress-1>", self.left_but_down)
drawing_area.bind("<ButtonRelease-1>", self.left_but_up)
toolbar = Frame(root,bd=1,relief = RAISED)
clearcanvas_img = Image.open("clearcanvas.png")
clearcanvas_icon = ImageTk.PhotoImage(clearcanvas_img)
clearcanvas_button = Button(toolbar, image=clearcanvas_icon, command = drawing_area.delete('all'))
clearcanvas_button.image = clearcanvas_icon
clearcanvas_button.pack (side = LEFT, padx=2, pady=2)
toolbar.pack(side = TOP, fill= X)
root = Tk()
paint_app = PaintApp(root)
root.mainloop()