This page intentionally left blank Python for Software Design


Case Study: Tkinter 19.1



tải về 1.38 Mb.
Chế độ xem pdf
trang75/83
Chuyển đổi dữ liệu13.08.2023
Kích1.38 Mb.
#55046
1   ...   71   72   73   74   75   76   77   78   ...   83
- Python for Software Design How to Think Like a Computer Scientist-Cambridge University Press (2009)

19
Case Study: Tkinter
19.1
GUI
Most of the programs we have seen so far are text-based, but many programs use
graphical user interfaces, also known as GUIs.
Python provides several choices for writing GUI-based programs, including
wxPython, Tkinter, and Qt. Each has pros and cons, which is why Python has not
converged on a standard.
The one I will present in this chapter is Tkinter because I think it is the easiest
to get started with. Most of the concepts in this chapter apply to the other GUI
modules, too.
There are several books and web pages about Tkinter. One of the best online
resources is An Introduction to Tkinter by Fredrik Lundh.
I have written a module called Gui.py that comes with Swampy. It provides a sim-
plified interface to the functions and classes in Tkinter. The examples in this chapter
are based on this module.
Here is a simple example that creates and displays a Gui:
To create a GUI, you have to import Gui and instantiate a Gui object:
from Gui import *
g = Gui()
g.title('Gui')
g.mainloop()
When you run this code, a window should appear with an empty gray square and the
title Gui. mainloop runs the event loop, which waits for the user to do something and
214


19.2 Buttons and Callbacks
215
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!


216
Case Study: Tkinter
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:
button2 = g.bu(text='No, press me!', command=make_label)
When you press this button, it should execute make_label and a new label should
appear.
The value of the command option is a function object, which is known as a callback
because after you call bu to create the button, the flow of execution “calls back”
when the user presses the button.
This kind of flow is characteristic of event-driven programming. User actions, like
button presses and key strokes, are called events. In event-driven programming, the
flow of execution is determined by user actions rather than by the programmer.
The challenge of event-driven programming is to construct a set of widgets and
callbacks that work correctly (or at least generate appropriate error messages) for
any sequence of user actions.
Exercise 19.1
Write a program that creates a GUI with a single button. When the button is pressed
it should create a second button. When that button is pressed, it should create a label
that says, “Nice job!.”
What happens if you press the buttons more than once? You can see my solution at
thinkpython.com/code/button_demo.py
19.3
CANVAS WIDGETS
One of the most versatile widgets is the Canvas, which creates a region for drawing
lines, circles, and other shapes. If you did Exercise 15.4 you are already familiar with
canvases.
The method ca creates a new Canvas:
canvas = g.ca(width=500, height=500)
width
and height are the dimensions of the canvas in pixels.


19.4 Coordinate Sequences
217
After you create a widget, you can still change the values of the options with the
config
method. For example, the bg option changes the background color:
canvas.config(bg='white')
The value of bg is a string that names a color. The set of legal color names is different
for different implementations of Python, but all implementations provide at least:
white
black
red
green
blue
cyan
yellow
magenta
Shapes on a Canvas are called items. For example, the Canvas method circle draws
(you guessed it) a circle:
item = canvas.circle([0,0], 100, fill='red')
The first argument is a coordinate pair that specifies the center of the circle; the
second is the radius.
Gui.py
provides a standard Cartesian coordinate system with the origin at the center
of the Canvas and the positive axis pointing up. This is different from some other
graphics systems where the the origin is in the upper left with the axis pointing down.
The fill option specifies that the circle should be filled in with red.
The return value from circle is an Item object that provides methods for modifying
the item on the canvas. For example, you can use config to change any of the circle’s
options:
item.config(fill='yellow', outline='orange', width=10)
width
is the thickness of the outline in pixels; outline is the color.
Exercise 19.2
Write a program that creates a Canvas and a Button. When the user presses the
Button, it should draw a circle on the canvas.
19.4
COORDINATE SEQUENCES
The rectangle method takes a sequence of coordinates that specify opposite corners
of the rectangle. This example draws a green rectangle with the lower left corner at


218
Case Study: Tkinter
the origin and the upper right corner at

tải về 1.38 Mb.

Chia sẻ với bạn bè của bạn:
1   ...   71   72   73   74   75   76   77   78   ...   83




Cơ sở dữ liệu được bảo vệ bởi bản quyền ©hocday.com 2024
được sử dụng cho việc quản lý

    Quê hương