用小部件退出ObjectListView

时间:2019-07-19 10:21:21

标签: oop objectlistview

我是Classes和OLV的新手。 我编写了一个功能齐全的独立程序,但通过SAVE&QUIT按钮退出OpenListView的调用不起作用。我认为是因为我没有关闭MainFrame实例?我只是想不出该怎么做-我所能做的就是退出/关闭框架中的一个窗口!

有一个有效的“文件>退出”按钮,但我希​​望“保存并退出”按钮也能工作。

import wx
from ObjectListView import ObjectListView, ColumnDefn
import os.path

########################################################################
class EntryObject(object):
    def __init__(self, oriWord, reWord):
        self.oriWord = oriWord
        self.reWord = reWord

########################################################################
class MainPanel(wx.Panel):
    #----------------------------------------------------------------------
    def __init__(self, parent):
        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)

        #Read the textFile data
        with open('textFile.txt','r') as f:
            entryList = f.readlines()
        self.userEntries = []
        #Manually strip out inverted commas and line feeds, then split the data into its parts
        for b in entryList:
            b=b.replace('"','')
            b=b.strip()
            oriWord,reWord = b.split(",")
            self.userEntries.append(EntryObject(oriWord,reWord))

        self.dataOlv = ObjectListView(self, wx.ID_ANY, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
        self.setWordChange()

        # Allow the cell values to be edited when double-clicked
        self.dataOlv.cellEditMode = ObjectListView.CELLEDIT_DOUBLECLICK

        # Save and Quit Button
        saveAndQuitBtn = wx.Button(self, wx.ID_ANY, "Save")
        saveAndQuitBtn.Bind(wx.EVT_BUTTON, self.saveAndQuit)

        # Reset Button - The original, unedited text is re-written to the OLV table
        resetBtn = wx.Button(self, wx.ID_ANY, "Reset")
        resetBtn.Bind(wx.EVT_BUTTON, self.resetControl)

        # Create some sizers
        mainSizer = wx.BoxSizer(wx.VERTICAL)        
        mainSizer.Add(self.dataOlv, 1, wx.ALL|wx.EXPAND, 5)
        mainSizer.Add(resetBtn, 0, wx.ALL|wx.LEFT, 5)
        mainSizer.Add(saveAndQuitBtn, 0, wx.ALL|wx.LEFT, 5)
        self.SetSizer(mainSizer)


    def saveAndQuit(self, event):
        """
        Write OLV data to a file 
        """
        #retrieve the data from the Olv
        data=self.dataOlv.GetObjects()
        #Write the data out to an empty file
        with open('textFile.txt','w') as f:
            for b in data:
                outp='"%s","%s"\n'%(b.oriWord,b.reWord)
                f.write(outp)
        print("The the file has been edited and saved!")        
        self.OnQuit(event)

    def OnQuit(self, event):
        self.Close() # doesn't do anything.
        self.Destroy() # closes an inner window of the frame only.


    def resetControl(self, event):
        """
        Ignore past edits and revert to teh original text file input 
        """
        #retrieve the data from the Olv
        with open('textFile.txt','r') as f:
            entryList = f.readlines()
        self.userEntries = []
        #Manually strip out inverted commas and line feeds, then split the data into its parts
        for b in entryList:
            b=b.replace('"','')
            b=b.strip()
            oriWord,reWord = b.split(",")
            self.userEntries.append(EntryObject(oriWord,reWord))

            self.dataOlv.SetObjects(self.userEntries)

    def setWordChange(self, data=None):
        self.dataOlv.SetColumns([
            ColumnDefn("Original Text", "left", 380, "oriWord"),
            ColumnDefn("Replacement Text", "left", 350, "reWord"),
        ])
        self.dataOlv.CreateCheckStateColumn()
        self.dataOlv.SetObjects(self.userEntries)


########################################################################
class MainFrame(wx.Frame):
    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, parent=None, id=wx.ID_ANY, 
                          title="User Dictionary", size=(800,400))
        self.panel = MainPanel(self)


        menuFile = wx.Menu()
        menuFile.Append(1, "&Help")
        menuFile.AppendSeparator()
        menuFile.Append(2, "E&xit")
        menuBar = wx.MenuBar()
        menuBar.Append(menuFile, "&File")
        self.SetMenuBar(menuBar)
        self.CreateStatusBar()
        self.SetStatusText("User created word and phrase-replacement table.")
        self.Bind(wx.EVT_MENU, self.OnHelp, id=1)
        self.Bind(wx.EVT_MENU, self.OnQuit, id=2)

    def OnQuit(self,event):
        self.Close()

    def OnHelp(self,event):
        wx.MessageBox("Edit this table by double-clicking on entries\nIf you make a mistake, simply press teh RESET button.",
                      "Using this Table:", wx.OK | wx.ICON_INFORMATION, self)


########################################################################
class App(wx.App):

#    def __init__(self, redirect=False, filename=None):
#        wx.App.__init__(self, redirect, filename)

    def OnInit(self):
        # create frame here
        frame = MainFrame()
        frame.Show(True)
        return True

#----------------------------------------------------------------------
def main():

    # Create a test file and save it to a common directory
    if os.path.exists("textFile.txt"):
        print("Test file exists... the program will continue using the file already on the system.")
    else:
        textFileEntries = "James,Jimmy\nFrank,Franky\nSally,Sal"
        with open('textFile.txt','w') as f:
            for line in textFileEntries:
                f.write(line)
        print("A new test file has been created")

    # Start the GUI
    app = App()
    app.MainLoop()


if __name__ == "__main__":
    main()

0 个答案:

没有答案