O'Reilly logo

Python Cookbook, 2nd Edition by David Ascher, Anna Ravenscroft, Alex Martelli

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

11.12. Copying Geometry Methods and Options Between Tkinter Widgets

Credit: Pedro Werneck

Problem

You want to create new Tkinter compound widgets, not by inheriting from Frame and packing other widgets inside, but rather by setting geometry methods and options from other widget to another.

Solution

Here is an example of a compound widget built by this approach:

from Tkinter import * class LabeledEntry(Entry): """ An Entry widget with an attached Label """ def _ _init_ _(self, master=None, **kw): ekw = { } # Entry options dictionary fkw = { } # Frame options dictionary lkw = {'name':'label'} # Label options dictionary skw = {'padx':0, 'pady':0, 'fill':'x', # Geometry manager opts dict 'side':'left'} fmove = ('name',) # Opts to move to the Frame dict lmove = ('text', 'textvariable', 'anchor','bitmap', 'image') # Opts to move to the Label dict smove = ('side', 'padx', 'pady', # Opts to move to the Geometry 'fill') # manager dictionary # dispatch each option towards the appropriate component for k, v in kw: if k in fmove: fkw[k] = v elif k in lmove: lkw[k] = v elif k in smove: skw[k] = v else: ekw[k] = v # make all components with the accumulated options self.body = Frame(master, **fkw) self.label = Label(self.body, **lkw) self.label.pack(side='left', fill=skw['fill'], padx=skw['padx'], pady=skw['pady']) Entry._ _init_ _(self, self.body, **ekw) self.pack(side=skw['side'], fill=skw['fill'], padx=skw['padx'], pady=skw['pady']) methods = (Pack._ _dict_ _.keys( ) + # Set Frame geometry methods ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required