动态获取小部件的内部 Tcl/Tk class 名称最可靠的方法是什么?

What's the most fail-proof way of dynamically acquiring a widget's internal Tcl/Tk class name?

动态获取 widget 的内部 Tcl/Tk class 名称最可靠的方法是什么?

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
    from tkinter import ttk
except:
    import Tkinter as tk
    import ttk


if __name__ == '__main__':
    root = tk.Tk()
    widget = ttk.Combobox(root)    # Would be "TCombobox" in this case
    widget.pack()
    root.mainloop()

尽管这只是基本小部件,请考虑深入继承此 widget 的 classes。

如果 widget 新创建的一种方法是使用 bindtags tagList 元素来获取,如:

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
    from tkinter import ttk
except:
    import Tkinter as tk
    import ttk


if __name__ == '__main__':
    root = tk.Tk()
    widget = ttk.Combobox(root)
    widget['values'] = widget.bindtags()[1]
    widget.current(0)
    widget.pack()
    root.mainloop()

但是,如果 bindtags() 返回的默认值 tagList 被修改,这个 失败。

您可以使用widget.winfo_class()方法:

winfo_class()

Returns the Tkinter widget class name for this widget. If the widget is a Tkinter base widget, widget.winfo_class() is the same as widget.__class__.__name__.


widget = ttk.Combobox()
print(widget.winfo_class())
# output: TCombobox