Home > Net >  tkinter: Why is "self._w" used to refer to a widget and not "self" in the "
tkinter: Why is "self._w" used to refer to a widget and not "self" in the "

Time:11-21

Below is a tkinter.ttk class extracted from /usr/lib/python3.8/tkinter/ttk.py. I noticed that in the line of code self.tk.call(self._w, "set", value), self._w is used and not self. This happens throughout the source code ttk.py. May I know why this is done?

class Spinbox(Entry):
    """Ttk Spinbox is an Entry with increment and decrement arrows

    It is commonly used for number entry or to select from a list of
    string values.
    """

    def __init__(self, master=None, **kw):
        """Construct a Ttk Spinbox widget with the parent master.

        STANDARD OPTIONS

            class, cursor, style, takefocus, validate,
            validatecommand, xscrollcommand, invalidcommand

        WIDGET-SPECIFIC OPTIONS

            to, from_, increment, values, wrap, format, command
        """
        Entry.__init__(self, master, "ttk::spinbox", **kw)


    def set(self, value):
        """Sets the value of the Spinbox to value."""
        self.tk.call(self._w, "set", value)

CodePudding user response:

Every widget represents an object in an embedded tcl interpreter. These objects have a unique name (eg: .frame.another_frame.some_button). This name is a string.

This widget name is also a command in the tcl interpreter. So, in order to call the underlying widget command, you must use the string name. self._w contains the string. Directly using self._w rather than converting self to a string is the most efficient way to do it.

  • Related