【问题标题】:tkinter: Why is "self._w" used to refer to a widget and not "self" in the "tk.call" method?tkinter:为什么在“tk.call”方法中“self._w”用来指代一个小部件而不是“self”?
【发布时间】:2021-11-20 15:50:35
【问题描述】:

下面是从/usr/lib/python3.8/tkinter/ttk.py 中提取的tkinter.ttk 类。我注意到在代码行self.tk.call(self._w, "set", value) 中使用了self._w 而不是self。这发生在整个源代码ttk.py。我可以知道为什么这样做吗?

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)

【问题讨论】:

  • self._w 存储小部件的名称,因此在tk.call() 中使用。但是,您也可以使用self只要将self 用作字符串,因为Misc.__str__()(所有小部件都继承自它)返回self._w

标签: python tkinter


【解决方案1】:

每个小部件都代表嵌入式 tcl 解释器中的一个对象。这些对象具有唯一的名称(例如:.frame.another_frame.some_button)。这个名字是一个字符串。

这个小部件名称也是 tcl 解释器中的一个命令。因此,为了调用底层小部件命令,您必须使用字符串名称。 self._w 包含字符串。直接使用self._w 而不是将self 转换为字符串是最有效的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-08
    • 2021-06-05
    • 2019-12-06
    • 2013-01-12
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多