Page 202 - thinkpython
P. 202

180                                               Chapter 19. Case study: Tkinter

                  responds accordingly. It is an infinite loop; it runs until the user closes the window, or
                  presses Control-C, or does something that causes the program to quit.
                  This Gui doesn’t do much because it doesn’t have any widgets. Widgets are the elements
                  that make up a GUI; they include:

                  Button: A widget, containing text or an image, that performs an action when pressed.
                  Canvas: A region that can display lines, rectangles, circles and other shapes.

                  Entry: A region where users can type text.

                  Scrollbar: A widget that controls the visible part of another widget.
                  Frame: A container, often invisible, that contains other widgets.

                  The empty gray square you see when you create a Gui is a Frame. When you create a new
                  widget, it is added to this Frame.



                  19.2 Buttons and callbacks

                  The method bu creates a Button widget:
                  button = g.bu(text=  'Press me. ')
                  The return value from bu is a Button object. The button that appears in the Frame is a
                  graphical representation of this object; you can control the button by invoking methods on
                  it.

                  bu takes up to 32 parameters that control the appearance and function of the button. These
                  parameters are called options. Instead of providing values for all 32 options, you can use
                  keyword arguments, like text= 'Press me. ', to specify only the options you need and use
                  the default values for the rest.

                  When you add a widget to the Frame, it gets “shrink-wrapped;” that is, the Frame shrinks
                  to the size of the Button. If you add more widgets, the Frame grows to accommodate them.



                  The method la creates a Label widget:
                  label = g.la(text=  'Press the button.  ')
                  By default, Tkinter stacks the widgets top-to-bottom and centers them. We’ll see how to
                  override that behavior soon.

                  If you press the button, you will see that it doesn’t do much. That’s because you haven’t
                  “wired it up;” that is, you haven’t told it what to do!

                  The option that controls the behavior of a button is command . The value of command is a
                  function that gets executed when the button is pressed. For example, here is a function
                  that creates a new Label:
                  def make_label():
                      g.la(text= 'Thank you. ')
                  Now we can create a button with this function as its command:
   197   198   199   200   201   202   203   204   205   206   207