-2

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

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()

This is only base widget though, please consider deep inheriting classes of this widget.

Nae
  • 14,209
  • 7
  • 52
  • 79

2 Answers2

1

You can use the widget.winfo_class() method:

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
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
0

If the widget's newly created one way would be to use bindtags tagList element to acquire as in:

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()

However, this would fail if the default tagList returned by bindtags() is modified.

Nae
  • 14,209
  • 7
  • 52
  • 79