How it works…

Each list comprehension iterates over the strings of the fields list. While labels use each item as the displayed text, entries only need the reference to the parent container—the underscore is a common idiom that means the variable value is ignored.

Starting from Python 3, zip returns an iterator instead of a list, so we consume the aggregation with the list function. As a result, the widgets attribute contains a list of tuples that can be safely iterated multiple times:

fields = ["First name", "Last name", "Phone", "Email"]
labels = [tk.Label(self, text=f) for f in fields]
entries = [tk.Entry(self) for _ in fields]
self.widgets = list(zip(labels, entries))

Now, we have to call the geometry manager on each tuple of widgets. With the enumerate function, we can track the index of each iteration and pass it as the row number:

for i, (label, entry) in enumerate(self.widgets):
label.grid(row=i, column=0, padx=10, sticky=tk.W)
entry.grid(row=i, column=1, padx=10, pady=5)

Note that we used the for i, (label, entry) in ... syntax because we must unpack the tuple generated with enumerate, and then unpack each tuple of the widgets attribute.

Within the print_info() callback, we iterate over widgets to print each label text with its corresponding entry value. To retrieve the labels' text, we used the cget() method, which allows you to get the value of a widget option by its name.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset