[Fwd: Re: Calling function from another module]
craf
prog at vtr.net
Thu Dec 16 07:33:16 EST 2010
--------- Mensaje reenviado --------
> De: Peter Otten <__peter__ at web.de>
> Para: python-list at python.org
> Asunto: Re: Calling function from another module
> Fecha: Thu, 16 Dec 2010 13:16:30 +0100
> Grupos de noticias: comp.lang.python
>
> craf wrote:
>
> > Hi.
> >
> > The query code is as follows:
> >
> > ------------------------------------------------------
> > import Tkinter
> > import tkMessageBox
> >
> >
> > class App:
> > def __init__(self, master):
> > master.protocol("WM_DELETE_WINDOW",quit)
> >
> >
> > def quit():
> > if tkMessageBox.askyesno('','Exit'):
> > master.quit()
> >
> >
> > master =Tkinter.Tk()
> > app = App(master)
> > master.mainloop()
> > -------------------------------------------------------
> >
> > As you can see, when I run and close the main window displays
> > a text box asking if you want to quit, if so, closes
> > application.
> >
> > Question:
> >
> > Is it possible to define the quit() function in another separate
> > module?.
> > I tried it, but it throws the error that the global name
> > 'master' is not defined.
>
> You can have the modules import each other and then access the master as
> <module>.master where you'd have to replace <module> with the actual name of
> the module, but that's a bad design because
>
> (1) you create an import circle
> (2) functions relying on global variables already are a bad idea
>
> Your other option is to pass 'master' explicitly and then wrap it into a
> lambda function (or functools.partial):
>
> $ cat tkquitlib.py
> import tkMessageBox
>
> def quit(master):
> if tkMessageBox.askyesno('','Exit'):
> master.quit()
>
>
> $ cat tkquit_main.py
> import Tkinter
>
> import tkquitlib
>
> class App:
> def __init__(self, master):
> master.protocol("WM_DELETE_WINDOW", lambda: tkquitlib.quit(master))
>
> master = Tkinter.Tk()
> app = App(master)
> master.mainloop()
>
> Peter
Hi Peter.
¡Right!. Your example can separate the creation of the interface to the
code execution. Thanks for your time.
Regards
Cristian
More information about the Python-list
mailing list