Search code examples
pythontkintertk-toolkitttk

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


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.


Solution

  • 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