CMU 15-112: Fundamentals of Programming and Computer Science
Class Notes: Graphics in Tkinter, Part 1
- We will only run graphics in Standard Python. These examples will not run in Brython.
- The standard Python documentation for tkinter can be hard to read. You can find our preferred documentation here (see chapter 8 on "The Canvas Widget").
- Create an Empty Canvas
Note: you need to know how to write your own draw() function, and how to use runDrawing(), but you do not need to know how to write runDrawing()!
from tkinter import * def draw(canvas, width, height): pass # replace with your drawing code! def runDrawing(width=300, height=300): root = Tk() root.resizable(width=False, height=False) # prevents resizing window canvas = Canvas(root, width=width, height=height) canvas.configure(bd=0, highlightthickness=0) canvas.pack() draw(canvas, width, height) root.mainloop() print("bye!") runDrawing(400, 200)Result:
- Canvas Coordinates We refer to pixels on the canvas in terms of x,y coordinates. However, the graphics canvas has one major difference from math coordinate planes: the y axis grows down instead of up. Thus, (0, 0) is at the top left corner of the canvas.
- Draw a Line
def draw(canvas, width, height): # create_line(x1, y1, x2, y2) draws a line from (x1, y1) to (x2, y2) canvas.create_line(25, 50, width/2, height/2)Result: