Tkinter menu

Fredrik Lundh fredrik at pythonware.com
Thu Dec 1 17:27:27 EST 2005


<gh14tq5 at yahoo.com> wrote:

> I'm writing a small GUI program in Python/Tkinter (my first Python
> program).  I want to make a menu which lists the names of a number of
> text files that my program uses/generates.  When I select one of the
> files from the menu, I would like a new window to open up a scroll box
> containing the file.  I was able to get it to work by hard a separate
> function for each file name in the addmenuitem for each file, but as the
> number of files grows, that gets to be tedious.  So I'm trying to write
> the menu bar as a loop, but I don't know how to get the file name passed
> to the function if the I use only one function call.

the easiest way to do this is to create a new function object for each
file, and use default argument binding to pass in the right filename:

    for file in self.allfiles:
        def callback(fname=file):
            self.showFile(fname, parent)
        self.showfilemenu_bar.addmenuitem('Show Files',
            'command',label=file, command=callback)

the "def" statement creates a new instance of the callback function for
each iteration.  the "fname" variable is bound to the current file object,
while "self" and "parent" are bound to the variables with the same names
in the outer scope.

</F>






More information about the Python-list mailing list