Class for custom Tkinter widget--difficulty

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Sep 17 16:37:44 EDT 2007


En Mon, 17 Sep 2007 17:11:03 -0300, Kevin Walzer <kw at codebykevin.com>  
escribi�:

> I'm trying to create a custom Tkinter widget class, and I'm having some
> difficulty getting it set up properly.
>
> The class is called MacToolbar, saved in its own module MacToolbar.py,
> and imported with this statement:
>
> 	import MacToolbar
>
> Here is the relevant portion of the class:
>
> ###relevant class code
>
> class MacToolbar:
>      def __init__(self, master):
>          self.tk.call("package", "require", "macsearchfield")
>          self.tk.call('package', 'require', 'tile')
>
>
>      def create(self):
>          self.baseframe = Tile.Frame(self, master)
>          self.baseframe.pack(side='top', fill='both', expand='no')
>
>
>      def toolbar(self):
>          self.create()
>          self.newframe = Tile.Frame(self.baseframe)
>          self.newframe.pack(fill='both', expand='yes')
>
>          self.buttonframe = Tile.Frame(self.newframe)
>          self.buttonframe.pack(side='top', fill='both', expand = 'yes')
>
>
> I'm a bit confused on how to call a class that is imported via a module.
> Both approaches I try produce errors:
>
> 	self.topframe = MacToolbar.toolbar(self.mainframe)
>   	self.topframe = MacToolbar.MacToolbar.toolbar(self.mainframe)

> [...] I was expecting to be able to use the standard Class.Method  
> notation in
> calling MacToolbar class methods, but it appears that this does not work
> at all: that's what I see in the first error above. Instead I have to
> use Module.Class.Method notation? I've never seen this before.
>
> Can someone point out what I am doing wrong, either in the construction
> of the class, the way it's imported, or in how I'm calling methods?

You have to create an instance, and then you call methods on that instance.
But toolbar() doesn't look like a method; both the create and toolbar  
methods appear to create the toolbar itself; probably you should move all  
that code into __init__.
Perhaps you should inherit from Frame?

Given the kind of mistakes you have, I suggest you read something about  
classes and object orientation in Python. (Maybe you have used a lot of  
classes, but perhaps this is the first class you *design*?)

-- 
Gabriel Genellina




More information about the Python-list mailing list