How it works...

As you may have noticed, both buttons use a partial function as callback. This is a utility from the functools module, which creates a new callable object that behaves like the original function, but with some fixed arguments. For instance, consider this statement:

tk.Button(self, command=partial(self.set_color, "fg"), ...)

The preceding statement performs the same action as the following statement:

tk.Button(self, command=lambda: self.set_color("fg"), ...)

We did this in order to reuse our set_color() method at the same time we introduce the functools module. These techniques are very useful in more complex scenarios, especially when you want to compose multiple functions and it is very clear that some arguments are already predefined.

A minor detail to keep in mind is that we shorthanded foreground and background with fg and bg, respectively. These strings are unpacked with ** when configuring the widget in this statement:

def set_color(self, option):
color = askcolor()[1]
print("Chosen color:", color)
self.label.config(**{option: color}) # same as (fg=color)
or (bg=color)

askcolor returns a tuple with two items that represent the selected color—the first one is a tuple of integers that represent the RGB values, and the second one is the hexadecimal code as a string. Since the first representation cannot be directly passed to the widget options, we used the hexadecimal format.

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

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