|
| 1 | +from tkinter import Tk, Canvas, Frame, Button, SUNKEN, LEFT, RIGHT |
| 2 | + |
| 3 | +lastx = 0 |
| 4 | +lasty = 0 |
| 5 | +identity = 0 |
| 6 | + |
| 7 | +# event handlers |
| 8 | +def up(): |
| 9 | + 'move pen up 10 pixels' |
| 10 | + global identity, y, canvas, lasty, lastx # y is modified |
| 11 | + identity += 1 |
| 12 | + canvas.create_line(x, y, x, y-10, tags='last'+str(identity)) |
| 13 | + y -= 10 |
| 14 | + lasty = 10 |
| 15 | + lastx = 0 |
| 16 | + |
| 17 | +def down(): |
| 18 | + 'move pen down 10 pixels' |
| 19 | + global identity, y, canvas, lasty, lastx # y is modified |
| 20 | + identity += 1 |
| 21 | + canvas.create_line(x, y, x, y+10, tags='last'+str(identity)) |
| 22 | + y += 10 |
| 23 | + lastx = 0 |
| 24 | + lasty = -10 |
| 25 | + |
| 26 | +def left(): |
| 27 | + 'move pen left 10 pixels' |
| 28 | + global identity, x, canvas, lastx, lasty # x is modified |
| 29 | + identity += 1 |
| 30 | + canvas.create_line(x, y, x-10, y, tags='last'+str(identity)) |
| 31 | + x -= 10 |
| 32 | + lasty = 0 |
| 33 | + lastx = 10 |
| 34 | + |
| 35 | +def right(): |
| 36 | + 'move pen right 10 pixels' |
| 37 | + global identity, x, canvas, lastx, lasty # x is modified |
| 38 | + identity += 1 |
| 39 | + canvas.create_line(x, y, x+10, y, tags='last'+str(identity)) |
| 40 | + x += 10 |
| 41 | + lasty = 0 |
| 42 | + lastx = -10 |
| 43 | + |
| 44 | +def clear(): |
| 45 | + global canvas |
| 46 | + canvas.addtag_all(all) |
| 47 | + canvas.delete(all) |
| 48 | + |
| 49 | + |
| 50 | +def delete(): |
| 51 | + global identity, canvas, x, y, lastx, lasty |
| 52 | + canvas.delete('last'+str(identity)) |
| 53 | + x += lastx |
| 54 | + y += lasty |
| 55 | + |
| 56 | +root = Tk() |
| 57 | + |
| 58 | +# canvas with border of size 100 x 150 |
| 59 | +canvas = Canvas(root, height=100, width=150, |
| 60 | + relief=SUNKEN, borderwidth=3) |
| 61 | +canvas.pack(side=LEFT) |
| 62 | + |
| 63 | +# frame to hold the 4 buttons |
| 64 | +box = Frame(root) |
| 65 | +box.pack(side=RIGHT) |
| 66 | + |
| 67 | +# the 4 button widgets have Frame widget box as their master |
| 68 | +button = Button(box, text='up', command=up) |
| 69 | +button.grid(row=0, column=0, columnspan=2) |
| 70 | +button = Button(box, text='left',command=left) |
| 71 | +button.grid(row=1, column=0) |
| 72 | +button = Button(box, text='right', command=right) |
| 73 | +button.grid(row=1, column=1) |
| 74 | +button = Button(box, text='down', command=down) |
| 75 | +button.grid(row=2, column=0, columnspan=2) |
| 76 | +button = Button(box, text='clear', command=clear) |
| 77 | +button.grid(row=3, column=0) |
| 78 | +button = Button(box, text='delete', command=delete) |
| 79 | +button.grid(row=3, column=1) |
| 80 | + |
| 81 | +x, y = 50, 75 # pen position, initially in the middle |
| 82 | + |
| 83 | + |
| 84 | +root.mainloop() |
| 85 | + |
0 commit comments