试图创建一个简单的绘画应用程序,我有一个按钮,当按下该按钮时,我希望清除画布,以便可以开始新的绘画。
我在tkinter界面中呈现了按钮,并且我在按钮中添加了与drawing_area.delete('all')
命令等效的canvas.delete('all')
命令,但是当我在画布上绘制并单击按钮时,似乎什么也没有发生。
不太确定我在哪里出错了,如果有人可以帮助我,那将非常好,我将应用程序的代码放在下面。
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()
答案 0 :(得分:0)
使用command=lambda: drawing_area.delete('all')
将起作用。
没有lambda,它只是在那里调用函数。但是您只需要在单击按钮时才能调用它。