Reputation: 1000
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.
Upvotes: 3
Views: 117
Reputation: 328870
Widget
extends Tkinter.Widget
extends BaseWidget
extends Misc
which contains:
__getitem__ = cget
def __setitem__(self, key, value):
self.configure({key: value})
You can find this in your Python's library folder; search for Tkinter.py
This is the code which implement the dict
interface. There is no implementation for attribute access which would use __getattr__()
and __setattr__()
.
As to why the Tk guys went this way? It's hard to say. Tk integration in Python is pretty old. Or the people felt that __getattr__()
with its quirks would cause more trouble.
Upvotes: 1
Reputation: 386382
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.
Upvotes: 4