Example 1-28. PP4E\Preview\tkinter103.py
from tkinter import *
from tkinter.messagebox import showinfo
def reply(name):
showinfo(title='Reply', message='Hello %s!' % name)
top = Tk()
top.title('Echo')
top.iconbitmap('py-blue-trans-out.ico')
Label(top, text="Enter your name:").pack(side=TOP)
ent = Entry(top)
ent.pack(side=TOP)
btn = Button(top, text="Submit", command=(lambda: reply(ent.get())))
btn.pack(side=LEFT)
top.mainloop()
As is, this example is just three widgets attached to the Tk main top-level window; later
we’ll learn how to use nested Frame container widgets in a window like this to achieve
a variety of layouts for its three widgets. Figure 1-6 gives the resulting main and pop-
up windows after the Submit button is pressed. We’ll see something very similar later
in this chapter, but rendered in a web browser with HTML.
Figure 1-6. Fetching input from a user
The code we’ve seen so far demonstrates many of the core concepts in GUI program-
ming, but tkinter is much more powerful than these examples imply. There are more
than 20 widgets in tkinter and many more ways to input data from a user, including
multiple-line text, drawing canvases, pull-down menus, radio and check buttons, and
scroll bars, as well as other layout and event handling mechanisms. Beyond tkinter
itself, both open source extensions such as PMW, as well as the Tix and ttk toolkits
now part of Python’s standard library, can add additional widgets we can use in our
Step 5: Adding a GUI | 45