Anthony Do
Anthony Do

Reputation: 1419

Python - GUI - Tkinter listboxes

i am having trouble loading one of my text files into my GUI. I have a load function(on the menubar), and have created a listbox.

The code for the loading the menu and the listbox:

class View(Listbox):
    def __init__(self, master):
        Listbox.__init__(self, master)      #makes view class listbox


class Controller(object):
    def __init__(self, master):
        """ Main interface:
        master - the top level window

        """
        self._master = master
        menubar = Menu(self._master)

        frame1 = Frame(self._master)
        frame1.pack(side=TOP, fill=BOTH, padx=5,expand=True)

        self._Listbox=View(frame1)
        self._Listbox.pack(side = TOP,fill=BOTH, expand = True,pady=20)

        menubar = Menu(self._master)
        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Open rooms file", command = self.file_open)


    def file_open(self):
        filename = tkFileDialog.askopenfilename() 

The load file works, but where is the text document being currently loaded? How can i display it on my listbox?

Upvotes: 0

Views: 2750

Answers (1)

mgilson
mgilson

Reputation: 310187

This works:

from Tkinter import *
import tkFileDialog

class View(Listbox):
    def __init__(self, master):
        Listbox.__init__(self, master)      #makes view class listbox


class Controller(object):
    def __init__(self, master):
        """ Main interface:
        master - the top level window
        """
        self._master = master

        frame1 = Frame(self._master)
        frame1.pack(side=TOP, fill=BOTH, padx=5,expand=True)

        self._Listbox=View(frame1)
        self._Listbox.pack(side = TOP,fill=BOTH, expand = True,pady=20)

        menubar = Menu(self._master)
        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Open", command = self.file_open)
        menubar.add_cascade(label='File',menu=filemenu)
        self._master.config(menu=menubar)

    def file_open(self):
        filename = tkFileDialog.askopenfilename()

        #insert each line in the file into the listbox
        with open(filename,'r') as f:
            for line in f:
                self._Listbox.insert(END,line)



if __name__ == "__main__":
    root=Tk()
    c=Controller(root)
    root.mainloop()

This is only slightly different than your code... First, I removed the first menubar = Menu(self._master) since it didn't really do anything. Second, I added a "cascade" menubar.add_cascade(label='File',menu=filemenu), third, I actually attached the menu to the root Tk window: self._master.config(menu=menubar)

Upvotes: 3

Related Questions