CMU 15-112: Fundamentals of Programming and Computer Science
Class Notes: Graphics in Tkinter, Part 1


Notes
  1. Create an Empty Canvas
  2. Canvas Coordinates
  3. Draw a Line

  1. 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:


  2. Canvas Coordinates
  3. 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.


  4. 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: