I was implementing a ttk progress bar yesterday and saw some code that I didn't quite understand.
A maximum value can be set for a progress bar by using something like the following:
progress_bar["maximum"] = max
I was expecting the ttk Progressbar object would use an instance variable to track the maximum value for a created object, but that syntax would look more like:
progres_bar.maximum = max
So my question is, what exactly is happening with the bracketed syntax here, what's the terminology, and where can I read more on this? When I looked at the Progressbar class, all I saw was
class Progressbar(Widget):
"""Ttk Progressbar widget shows the status of a long-running
operation. They can operate in two modes: determinate mode shows the
amount completed relative to the total amount of work to be done, and
indeterminate mode provides an animated display to let the user know
that something is happening."""
def __init__(self, master=None, **kw):
"""Construct a Ttk Progressbar with parent master.
STANDARD OPTIONS
class, cursor, style, takefocus
WIDGET-SPECIFIC OPTIONS
orient, length, mode, maximum, value, variable, phase
"""
Widget.__init__(self, master, "ttk::progressbar", kw)
I see there's a "widget-specifc option", but I don't understand how progress_bar["maximum"] = max sets that value, or how it's stored.
What is happening is that the ttk module is a thin wrapper around a tcl interpreter with the tk package installed. Tcl/tk has no concept of python classes.
In tcl/tk, the way to set an attribute is with a function call. For example, to set the maximum attribute, you would do something like this:
.progress_bar configure -maximum 100
The ttk wrapper is very similar:
progress_bar.configure(maximum=100)
For a reason only known to the original tkinter developers, they decided to implement a dictionary interface that allows you to use bracket notation. Maybe they thought it was more pythonic? For example:
progress_bar["maximum"] = 100
Almost certainly, the reason they didn't make these attributes of the object (eg: progress_bar.maximum = 100) is because some tcl/tk widget attributes would clash with python reserved words or standard attributes (for example, id). By using a dictionary they avoid such clashes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With