for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)
feet_entry.focus()
root.bind('<Return>', calculate)
The preceeding three lines help put some nice finishing touches on our user interface.
The first line walks through all of the widgets that are children of our content frame,and adds a little bit of padding around each, so they aren't so scrunched together.We could have added these options to each "grid" call when we first put the widgetsonscreen, but this is a nice shortcut.The second line tells Tk to put the focus on our entry widget. That way the cursor willstart in that field, so the user doesn't have to click in it before starting to type.
The third line tells Tk that if the user presses the Return key (Enter on Windows) anywherewithin the root window, that it should call our calculate routine, the same as if theuser pressed the Calculate button.
def calculate(*args):
try:
value = float(feet.get())
meters.set((0.3048 * value * 10000.0 + 0.5)/10000.0)
except ValueError:
pass
Here we define our calculate procedure, which is called either when the user pressesthe Calculate button, or hits the Return key. It performs the feet to meterscalculation, taking the number of feet from our entry widget, and placing the resultin our label widget.
Say what? It doesn't look like we're doing anything with those widgets! Here's wherethe magic "textvariable" options we specified when creating the widgets come into play. We specified the global variable "feet" as the textvariable for the entry, which meansthat anytime the entry changes, Tk will automatically update the global variable feet.Similarly, if we explicitly change the value of a textvariable associated with a widget(as we're doing for "meters" which is attached to our label), the widget will automaticallybe updated with the current contents of the variable. Slick.
root.mainloop();This final line tells Tk to enter its event loop, which is needed to make everything run.