Basj
Basj

Reputation: 46293

Sticky=W by default for all objects (Tkinter)

Is it possible to have sticky=W by default for grid positionning in tkinter ?

Label(master, text="First").grid(row=0, sticky=W)
Label(master, text="Second").grid(row=1, sticky=W)
...

This would prevent from setting sticky=W 20 times ...

Upvotes: 1

Views: 1266

Answers (3)

Bryan Oakley
Bryan Oakley

Reputation: 386285

No, there is no built-in way to do this. You could create your own helper function, or you could subclass every widget, or you could redefine the core grid command via monkeypatching, but why? All it does is save you a couple keystrokes, and it makes your code harder to understand by others, since your default isn't the default.

Upvotes: 1

mgilson
mgilson

Reputation: 310097

Seems like a job for a helper function:

def grid(widget, sticky=W, **kwargs):
    widget.grid(sticky=sticky, **kwargs)

grid(Label(master, text="First"), row=0)
...

You probably could do some hackery and replace tkinter.Widget.grid with a wrapper around tkinter.Widget.grid ;-). But that's more complicated and limiting than this solution IMHO.

Upvotes: 2

alko
alko

Reputation: 48357

I would subclass Label:

class LabelW(Label):
    def grid(self, **options):
        options['sticky'] = options.get('sticky') or 'W'
        super(LabelW, self).grid(**options)

LabelW(master, text="First").grid(row=0)

Upvotes: 0

Related Questions