Page 269 -
P. 269

tkinter event loop


           tkinter gives you the event loop for free


           In order to process events efficiently, GUIs employ an event loop. Event
           loops watch and wait for events, calling a piece of code each time an
           event occurs. If you think about the current TVN Game Show program,
           it already has a very basic event loop that waits for the host to press 1, 2,
           or 0. The program then calls some code before waiting again for another
           key-press event from the host. To implement this in code, you used a while
           loop:


                    while choice != '0':
                        if choice == '1':
                            number_asked = number_asked + 1
                            number_correct = number_correct + 1
                                                                                           Click on the close
                                                                                           box to terminate
                                                                                           this application.
           In tkinker, you don’t need to write a while loop like you did for your
           non-GUI program. In tkinter, call the mainloop() method instead:
                         Import everything from
                         the tkinter module.


                       from tkinter import *
              Give the                Create a tkinter application     These five lines of
                                      window called “app”.
              window a   app = Tk()                                     Python/tkinter code
              name.    app.title("Your tkinter application")            produce this GUI.
                       app.geometry('450x100+200+100')
         Provide window    app.mainloop()
         coordinates and
          size values.     Start the tkinter event loop.



           To add a button to your application, use code like this, being sure to put
           these two lines of code before the call to mainloop():


                                                                                    The button’s been
                   b1 = Button(app, text = "Click me!", width = 10)
                                                                                    added to the GUI.
                   b1.pack()

           Add a button to      The pack() method links
           the window and give   the newly created button
           it some text and a   to the existing window.
           width value.

           234    Chapter 7
   264   265   266   267   268   269   270   271   272   273   274