我知道这可能是有史以来最简单的问题。但是,我开始学习Tkinter,我不知道当鼠标单击GUI时如何引用事件。在
当我点击画布时,我想画一些点。我不能在paint函数中引用canvas变量。在
这段代码基于SO中的问题
每当我尝试这个例子时,paint函数中就会出现一个错误NameError: name 'canvas' is not defined;def main():
master = Tk()
# Right side of the screen / img holder
right_frame = Frame(master, width=500, height=500, cursor="dot")
right_frame.pack(side=LEFT)
# Retrieve image
image = Image.open("./image/demo.JPG")
image = image.resize((800, 700), Image.ANTIALIAS)
photo = ImageTk.PhotoImage(image)
# Create canvas
canvas = Canvas(right_frame, width=800, height=700)
canvas.create_image(0, 0, image=photo, anchor="nw")
canvas.pack()
canvas.bind("", paint)
message = Label(right_frame, text="Press the mouse to draw")
message.pack(side=BOTTOM)
mainloop()
def paint(event):
python_green = "#476042"
x1, y1 = (event.x - 1), (event.y - 1)
x2, y2 = (event.x + 1), (event.y + 1)
canvas.create_oval(x1, y1, x2, y2, fill=python_green)
if __name__ == "__main__":
main()