bembry.org
Home / Technology / Python / Notes

Tkinter Lesson 3 Notes: Using bind() To Make it Work

  • Concepts
    • To add functionality to a GUI you must:
    • Define an initializing event
      • What did the user do?
      • press a key, click a button, move the mouse
    • Define a function
      • What should the program do in response?
      • execute a function, launch a new window, end program
    • Associate the event and function with part of the GUI
      • To which widget does this behavior apply?
      • Does this feature apply to the whole window or application?
  • bind()
    • The bind() method ties together a widget, a user action, and an event
    • The bind() method takes two arguments:
      • sequence (the user action that triggers an event)
      • function (the function to run when triggered)
    • A function must be defined before it is called by bind()
  • Sample bind()
      from Tkinter import *
      root = Tk()
      btn = Button(root, text = "End")
      btn.grid()
      def stop(event):
          root.destroy()
      btn.bind('<Button-1>', stop)
    • When the button is clicked, the window is destroyed.
    • Notice that the function stop() takes "event" as an argument. The event is some data passed automatically from bind to the function. If you do not list it as a parameter, the function will crash.
    • The first argument in bind() is a string in quotation marks.
    • Note that the function stop is called without parenthesis

    Part 1: What are you binding to?
    • What to bind() with
      • Functions can be bound to a widget or to a whole window.
      • If a function is specific to a widget, bind it to the widget
        • Button is pressed, function is called
        • [Enter] button pressed while user is typing in Entry box, function is called
      • If a function applies to the window as a whole, bind it to the root window
        • Pressing [F1] brings up a help menu
        • Pressing [Delete] destroys the window
    • Binding Example
        deadlybox screenshot from Tkinter import *
        root = Tk()
        Label(root, text = "Deadly Box").grid()
        def stop(event):
            root.destroy()
        box = Entry(root, width=20)
        box.grid()
        root.bind('9', stop)
        box.bind('X', stop)
      • If the user types "X" while in the Entry box, the window will close. Hitting "X" at any other time will have no effect.
      • If the user presses the "9" key at any time, the window will close.

    Part 2: What event are you watching for?
  • Event Types
    • Events are the things that happen and trigger a response. They are the first argument in a bind() call.
        btn.bind('event', function)
    • There are three basic types of events that bind() can watch out for:
      • mouse events (click, mouse enters window, mouse moves)
      • keyboard events (key pressed, key combination pressed)
      • Environment changes (window resized, image changes, etc.)
    • To bind a function with an event, you must use a "sequence" keyword, or a combination of sequence keywords.
  • Some Sequence Event Keywords
    • Mouse Sequences
      • <Enter> -Mouse enters field of widget
      • <Leave> -Mouse leaves field of widget
      • <Button-1> -Left mouse button clicked
      • <Button-3> -Right mouse button
      • <Double-Button-1> - Double click left mouse button
      • <B1-Motion> -Mouse moved while left button is held down.
      • <ButtonRelease> - Mouse button has been let go.
      • example:
        btn.bind('<Button-1>', stop)
    • Keyboard Sequences
      • <Key> -any key has been pressed
      • <KeyRelease> -any key has been released
      • <Return> - [Enter] key pressed
      • X -A capital "X" pressed.
      • example:
        root.bind('<Return>', func)
        root.bind('R', func)
  • Anatomy of a Event Sequence
    • Event sequences take the form <Event-modifier>
    • Event sequence combinations are created by adding a hyphen and a new keyword.

        <Control-Shift-space>
        <Shift-Button-1>
    • The keywords are case sensitive
    • Alphabet letters can by indicated without < >, everything else needs to be inside < >
  • Keyboard Event Reference

    BackSpace
    Break
    Control_L
    Delete
    Down
    End
    Escape
    F1, F2 …
    Home
    Insert
    Left
    Num_Lock
    Print
    Return
    Right
    Shift_L
    Shift_R
    Tab
    Up
     
    backslash
    bracketleft
    bracketright
    colon
    comma
    dollar
    equal
    exclam
    minus
    numbersign
    percent
    period
    plus
    slash
    space
     
    Keypad Buttons
    KP_1 , KP_2 …
    KP_Add
    KP_Decimal
    KP_Divide
    KP_Enter
    KP_Equal
    KP_Multiply
    KP_Subtract
  • Special Event Sample

      from Tkinter import *
      root = Tk()
      Label(root, text = "Deadly Box").grid()
      def stop(event):
          root.destroy()
      box = Entry(root, width=20)
      box.grid()
      root.bind('<Control-F10>', stop)
      root.bind('<Shift-space>', stop)
    • Two special combinations are set up. If the user holds down shift and presses the space bar, or if he holds control and presses F10, the window will disappear.

    Part 3: What does the program do when triggered?
    • Generally Available Methods
      • widget.configure()
        This will change whatever configuration options you specify. The changes will automatically appear on the screen.
      • widget.destroy()
        This will destroy the widget and remove it from the GUI.
      • These methods can be used on most widgets
    • .configure() Example
        import random
        from Tkinter import *
        root = Tk()
        def colorchange(event):
            colors = ['red', 'blue', 'green', 'yellow', 'orange']
            color = random.choice(colors)
            btn.configure(bg=color)
        btn = Button(root, text= "Chameleon")
        btn.grid()
        btn.bind('<Button-1>', colorchange)
        Before pushing button
        A random color
      • The button is bound to the colorchange function. This function randomly picks a color and uses btn.configure() to apply this color to the button background.
      • The .configure() method can be used on any option of a widget.
    • Entry and Text Methods
      • widget.get(index1, index2)
        Gets the text currently in the Entry or Text widget. Can specify a start and end index number, or leave blank to get everything.
      • widget.insert(index1, text)
        Insert text into the widget at the given index point.
      • widget.delete(index1, index2)
        Delete the characters from index1 to index2. This method requires both indexes.
    • Text Method Examples
      Screenshot from Tkinter import *
      root = Tk()
      lbl = Label(root, text = "Your Text Here", bg = 'blue', fg= 'white')
      lbl.grid()
      textbox = Entry(root, width="20")
      textbox.grid()
      def lblupdate(event):
          newtext = textbox.get()
          textbox.delete(0, len(newtext))
          lbl.configure(text = newtext)
      textbox.bind('<Return>', lblupdate)
    Restricted access