MC logo

Canvas With Events


CS 233 Python Lecture Examples

<< Download
#!/usr/bin/python2

#
# Rectangle with actions attached to the objects.
#

from Tkinter import *

main = Tk()

#
# Simple actions.
def oval_act(obj):
    print 'In Oval'

def rect_act(obj):
    print 'In Rectangle'

# Create the canvase.
canvas = Canvas(main, width=300, height=300, bg='blue')
canvas.pack()

# Draw some shapes and bind them to button events.
oval = canvas.create_oval(10, 30, 150, 100, fill='white')
canvas.tag_bind(oval, '<Button-1>', oval_act)
rect = canvas.create_rectangle(100, 130, 250, 250, fill='red')
canvas.tag_bind(rect, '<Button-1>', rect_act)

main.mainloop()

<<