Suduko
Introduction to Software Engineering (CSSE 1001)
Canvas
A tkinter Canvas is a window in which we can draw.
The following can be drawn in canvases:
- ▶ arc bitmap
- ▶ images
- ▶ lines
- ▶ polygons
- ▶ rectangles
- ▶ text
- ▶ ovals
- ▶ window
tk.Canvas
root = tk.Tk()
canvas = tk.Canvas(
root,
width=100,
height=100,
bg="pink"
)
canvas.pack()
root.mainloop()We assume the above has been executed from now on and will insert new code before root.mainloop().
tk.Canvas.create_text
Note we use the graphics coordinate system where the top-left corner is (0, 0) and increasing y moves south.
canvas.create_text(
50, 100,
text="*",
)
canvas.create_text(
50, 100,
text="(50,100)",
anchor=tk.NW
)tk.Canvas.create_line
canvas.create_line(
50, 50,
100, 100,
fill="blue",
width=10
)tk.Canvas.create_rectangle
canvas.create_rectangle(
50, 50, # north-west corner
100, 100, # south-east corner
width=1 # border width
)
canvas.create_rectangle(
125, 150, 175, 175,
fill="light blue", # fill colour
width=10
)
canvas.create_rectangle(
150, 10, 190, 80,
fill="light green",
width=0
)tk.Canvas.create_window
tkinter widgets can be placed in canvases using window.
window = canvas.create_window(
50, 50,
width=100,
height=50,
window=tk.Button(text="Press Me"), # any widget can go here
anchor=tk.NW
)bind in tk.Canvas
We can bind inside canvases.
def handler(event):
print(f"{event.x} {event.y}")
canvas.bind("<Button>", handler)Clicking inside the canvas produces in the REPL:
178 155
81 89
151 83Inheritance
Do not forget that tkinter objects are objects which we can use for inheritance.
class View(tk.Canvas):
def __init__(self, master: tk.Tk, side: int, **kwargs) -> None:
super().__init__(master,
width=side,
height=side,
bg="pink",
**kwargs) # keyword arguments
self.create_text(50, 50, text="*", fill="black")
root = tk.Tk()
view = View(root, 200)
view.pack()
root.mainloop()Abstract Grid
For example, we can have an AbstractGrid class which inherits from a Canvas that extends it to include methods that interface with the canvas as if it were divided into a grid of smaller and equally sized rectangles.
class AbstractGrid(tk.Canvas):
"""A type of tkinter Canvas that provides support for
using the canvas as a grid (i.e. a collection of
rows and columns)."""Sudoku Game — A tkinter Canvas
A full Sudoku game can be implemented on top of such a grid canvas.