falconcodingclub

View project on GitHub

Intro to Event Driven Programming

Event drien programming is where you write code to respond to actions. This is a slightly different style that is especially pervadsivive in User Interface programming. We can learn the basics using the turtle program.

Using tkinter

We use tkinter to do the initial python user interface programming. Some basics about tkinter:

  1. Initialize Tk and create a canvas
    root = tkinter.tk
    cv = tkinter.Canvas(root, width=600, height=600)
    
  2. Implement handler
    def clickHandler(x, y):
     t.goto(x, y)
    screen.onclick(clickHandler)
    tkinter.mainloop()
    

So every time the click event is triggered the function ‘clickHandler’ is called. What else can the students do with that basic information? We like to integrate it with the previous shape exercises and ultimately add buttons and controls.

Adding Buttons

A quick example of adding buttons is in our draw app. We can add a quit button and a field to set the width of the string.

  1. Create the button frame
    button_frame = tkinter.Frame(root)
    button_frame.pack(side=tkinter.RIGHT, fill=tkinter.BOTH)
    
  2. Add the point size field
    pointLabel = tkinter.Label(button_frame, text="Width")
    pointLabel.pack()
    pointSize = tkinter.StringVar()
    pointEntry = tkinter.Entry(button_frame, textvariable=pointSize)
    pointEntry.pack()
    pointSize.set(str(1))
    
  3. Update the clickHandler to set the width with the current value
    t.width(int(pointSize.get()))
    
  4. Add a quit button
    def quitHandler():
     root.destroy()
     root.quit()
    quitButton = tkinter.Button(button_frame, text="Quit", command=quitHandler)
    quitButton.pack()
    

Advanced Challenge

Have the students use the above to create buttons for different shape templates.