tkinter: making widgets instance or not?

John McMonagle jmcmonagle at velseis.com.au
Tue Jun 6 19:36:23 EDT 2006


On Wed, 2006-06-07 at 09:27 +1000, John McMonagle wrote:
> On Tue, 2006-06-06 at 19:42 +0000, John Salerno wrote:
> > Fredrik Lundh wrote:
> > 
> > > however, if you need to access a widget later on, it might be a good 
> > > idea to save a reference to it somewhere...
> > 
> > To follow up on that point, I have the following code now. I have two 
> > questions about it:
> > 
> > 1. Can I somehow make the passing of 'master' to the draw_entry method 
> > automatic, so I don't have to type it each time I call the function?
> > 
> > 2. Related to your comment, the obvious problem here is that it doesn't 
> > save references to the text box names, so I can't access them later. Is 
> > there still a way to automate the process like I've done, but have each 
> > entry field have a separate name?
> > 
> > Thanks.
> > 
> > ---------------
> > 
> > import Tkinter as tk
> > 
> > 
> > class App:
> > 
> >      def __init__(self, master):
> >          self.draw_entry(master, 'First Name:')
> >          self.draw_entry(master, 'Last Name:')
> > 
> >      def draw_entry(self, master, label_text):
> >          frame = tk.Frame(master, bd=4)
> >          frame.pack()
> >          self.label = tk.Label(frame, text=label_text, width=10)
> >          self.label.pack(side=tk.LEFT)
> >          self.entry = tk.Entry(frame)
> >          self.entry.pack(side=tk.LEFT)
> > 
> > 
> > root = tk.Tk()
> > app = App(root)
> > root.resizable(width=False, height=False)
> > root.mainloop()
> > -- 
> 
> 
> Try this:
> 
> import Tkinter as tk
> 
> class App:
> 
>     def __init__(self, master):
>         self.parent = master
>         self.entry1 = self.draw_entry('First Name:')
>         self.entry2 = self.draw_entry('Last Name:')
>         
>     def draw_entry(self, label_text):
>         frame = tk.Frame(self,parent, bd=4)

Sorry - typo.  Should reas self.parent  not self,parent

>         frame.pack()
>         label = tk.Label(frame, text=label_text, width=10)
>         label.pack(side=tk.LEFT)
>         entry = tk.Entry(frame)
>         entry.pack(side=tk.LEFT)
>         return entry
> 
> root = tk.Tk()
> app = App(root)
> root.resizable(width=False, height=False)
> root.mainloop()
> 
> 
> 
> -- 
> This message has been scanned for viruses and
> dangerous content by MailScanner, and is
> believed to be clean.
> 


-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.




More information about the Python-list mailing list