An easily extensible class, inheriting from Canvas, which can be used to define geometry in a more mathematical way. So rather than specify a circle from 2 points you give a radius and a centre. These could have colour as a keyword argument but personally I always want to specify the colour.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | #==============================================================================
class Geometry(Canvas):
def __init__(self, parent, **kwargs):
# Tkinter doesn't support super(...) type initialisation
Canvas.__init__(self, parent, kwargs)
def draw_point(self, point, colour):
self.create_oval(
point[0] - 2,
point[1] - 2,
point[0] + 2,
point[1] + 2,
fill=colour,
outline=""
)
def draw_circle(self, centre, radius, colour):
# makes an oval, takes the top left coordinate and the bottom right
self.create_oval(
int(centre[0] - radius),
int(centre[1] - radius),
int(centre[0] + radius),
int(centre[1] + radius),
outline=colour,
fill=""
)
# draw the centre
self.draw_point(centre, colour)
def draw_line(self, point, second_point, colour):
self.create_line(
point[0],
point[1],
second_point[0],
second_point[1],
fill=colour
)
def draw_polygon(self, points, colour):
# tkinter wants the points like x0, y0, x1, y1, ... we give it as
# [(x0, y0), (x1, y1), ...]
tkinter_compatible_points = list()
for point in points:
tkinter_compatible_points.append(point[0])
tkinter_compatible_points.append(point[1])
self.create_polygon(
*tkinter_compatible_points,
fill="",
outline=colour
)
|
This will work in python 2.* or 3.* the only difference is in 3.* Tkinter is renamed tkinter.
This will fix it.
import sys
# renamed module in python 3
if (sys.version_info[:2] < (3,0)):
from Tkinter import *
else:
from tkinter import *