Search code examples
pythonpython-3.xtkinterdefaultdefault-value

How can you change the default anchor, relx and rely for placing tkinter widgets?


Many widgets in my program are placed like so:

widget.place(relx=0.5, rely=0.5, anchor=CENTER)

So, I wanted to make this the default setup. I have tried:

root.option_add("*anchor", "center")#Putting CENTER returns an error
root.option_add("*relx", "0.5")
root.option_add("*rely", "0")

However, this does not work.

How could I achieve this?


Solution

  • You can't change the default options without overriding the method, but a viable workaround would be simply defining a variable for that customization and simply pass that to the widgets that use it:

    try:                        # In order to be able to import tkinter for
        import tkinter as tk    # either in python 2 or in python 3
    except ImportError:
        import Tkinter as tk
    
    
    if __name__ == '__main__':
        root = tk.Tk()
        customization = dict(relx=0.5, rely=0.5, anchor='center')
        my_list_of_widgets = list()
        for i in range(30):
            my_list_of_widgets.append(tk.Label(root, text=i))
            my_list_of_widgets[i].place(**customization)
        tk.mainloop()