pythontkinterwidgetkeyword-argument

How to iterate through all Keyword Arguments of tk.Button


import tkinter as tk

def get_button_kwargs():
    button_kwargs = []
    for param in tk.Button.__init__.__code__.co_varnames:
        if param != 'self':
            button_kwargs.append(param)
    return button_kwargs

button_args = get_button_kwargs()

print("Available keyword arguments for tk.Button:")
for arg in button_args:
    print(arg)

Im trying to print keyword arguments of Button , like, bd, bg, activebackground color etc

but this prints only master cnf kw

On further inspecting I found that tk.button inherits from Widget class and widget class inherits BaseWidget class but still i dont have any idea how to proceed further


Solution

  • There isn't a way to get the python keyword arguments for a widget class since most of them are not explicitly defined in the various classes. The keyword arguments are passed to the underlying tcl interpreter with just a small modification.

    If you want a list of all configurable options, you can iterate over the results of a call to the configure method of a widget. It returns a dictionary of options, where the key are the available options.

    Some of the values will be a tuple of two values, some will be a tuple of five. If it is a tuple of two, the key is a synonym for another option. For example, "bg" will return ('bg', '-background') to designate that "bg" is a synonym for "background".

    So, to write a function that returns all keyword arguments but avoiding synonyms, you can iterate over the values and only return keys for which the value is a 5-tuple.

    def get_button_kwargs():
        button = tk.Button()
        options = button.configure()
        options = [k for k,v in options.items() if len(v) == 5]
        button.destroy()
        return options