Display file names in Tkinter Listbox

John McMonagle jmcmonagle at NO.SPAM.velseis.com.au
Thu May 20 01:36:59 EDT 2010


Rick at home.com wrote:
> Hello,
> 
> My first attenpt at a simple  python Tkinter application. I wanted to
> see how to load file names into a listbox from a menu. This is what I
> got until the part of displaying the file names in a listbox, which I
> could not figfure out how to do?
> 
> Any help would be appreciated. Trying to do this as simple as possible
> to understand.
> 
> The "print fileNames" does work but how to display it in listbox?
> 
> from Tkinter import *
> from tkFileDialog   import askopenfilenames
> 
> class MyCode:
>    def __init__(self):
>       root = Tk()
>       
>       menubar = Menu(root)
>       filemenu = Menu(menubar)
>       
>       lbox = Listbox(root, width=50).pack()

Your problem is the above line of code.

Here you are assigning the return value of the pack (None if I recall).

Later when you want to put things in the Listbox you don't have the
widget reference anymore.

It's probably a good idea to make the Listbox widget an attribute of
your class so you can use it in class methods without having to pass it
as an argument.

So, change the above line of code to:

        self.lbox = Listbox(root, width=50)
        self.lbox.pack()

>       
>       menubar.add_cascade(label='File', menu=filemenu)
>       filemenu.add_command(label='New Project')
>       filemenu.add_command(label='Load Files...', command=self.OnLoad)
>       
> 
>       filemenu.add_command(label='Exit', command=root.quit)
>       
>       root.config(menu=menubar)
>       
>       root.mainloop()
>       
>       
>    def OnLoad(self):
>       fileNames = askopenfilenames(filetypes=[('Split Files', '*')])
>       print fileNames
> 

Now that you've got a reference to your Listbox widget that is an
attribute of your class, you should be able to insert the file names
into the Listbox like so.

        self.lbox.insert(0, fileNames)

Regards,

John



More information about the Python-list mailing list