【问题标题】:wxpython, open file and display text into textctrl areawxpython,打开文件并将文本显示到 textctrl 区域
【发布时间】:2013-04-12 14:10:42
【问题描述】:

wxpython 很新,所以我正在努力解决这个问题。借助教程和努力学习,我有了一点办法。

我的文件菜单中有一个“打开”,我正在尝试获取它,以便当我打开文件时,文件中的文本将显示在我的多行 textctrl 框中

我尝试了一些位,例如 WriteText() 和 SetValue(),但无法显示。

import wx
import os



class MainWindow(wx.Frame):
def __init__(self, parent, title):
    self.dirname=''
    super(MainWindow, self).__init__(parent, title=title, size=(450, 450))
    self.CreateStatusBar() # A Statusbar in the bottom of the window
    global urlFld

    self.InitGUI()
    self.Centre()
    self.Show()

def InitGUI(self):

    #MENUS
    fileMenu = wx.Menu()  #create menu for file
    viewMenu = wx.Menu()  #create a menu for view
    helpMenu = wx.Menu()  #create a menu for help

    #FILE MENU
    menuOpen = fileMenu.Append(wx.ID_OPEN, "&Open"," Open a file to edit")  #add open to File
    menuExit = fileMenu.Append(wx.ID_EXIT, "E&xit"," Terminate the program")  #add exit to File

    #VIEW MENU
    menuView = viewMenu.Append(wx.ID_ANY, "TODO:", "Still to do")

    #HELP MENU
    menuAbout = helpMenu.Append(wx.ID_ABOUT, "&About", "About this program")  #add about menu item

    #MENUBAR
    menuBar = wx.MenuBar()
    menuBar.Append(fileMenu,"&File") # Adding the "filemenu" to the MenuBar
    menuBar.Append(viewMenu, "&View")
    menuBar.Append(helpMenu, "&Help")
    self.SetMenuBar(menuBar)  # Adding the MenuBar to the Frame content.

    '''#TOOLBAR
    toolbar = self.CreateToolBar()
    toolOpen = toolbar.AddLabelTool(wx.ID_OPEN, "Open", wx.Bitmap("open.png"))
    toolExit = toolbar.AddLabelTool(wx.ID_EXIT, "Exit", wx.Bitmap("blah.png"))'''


    #MENU EVENTS
    self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
    self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
    self.Bind(wx.EVT_MENU, self.OnExit, menuExit)

    '''#TOOLBAR EVENTS
    self.Bind(wx.EVT_TOOL, self.OnExit, toolExit)
    self.Bind(wx.EVT_TOOL, self.OnOpen, toolOpen)'''


    #PANEL
    panel = wx.Panel(self)

    panel.SetBackgroundColour('#ededed')
    vBox = wx.BoxSizer(wx.VERTICAL)

    hBox = wx.BoxSizer(wx.HORIZONTAL)
    hBox.Add(wx.StaticText(panel, label="File:"), flag=wx.TOP, border=3)
    hBox.Add(wx.TextCtrl(panel), 1, flag=wx.LEFT, border=10)
    checkBtn = wx.Button(panel, -1, "Check")
    self.Bind(wx.EVT_BUTTON, self.checkBtnClick)
    hBox.Add(checkBtn, 0, flag=wx.LEFT, border=10)
    vBox.Add(hBox, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)
    vBox.Add((-1, 10))

    hBox2 = wx.BoxSizer(wx.HORIZONTAL)
    hBox2.Add(wx.StaticText(panel, label="URLs:"))
    vBox.Add(hBox2, flag=wx.LEFT, border=10)
    vBox.Add((-1, 5))

    hBox3 = wx.BoxSizer(wx.HORIZONTAL)
    urlFld = wx.TextCtrl(panel, style=wx.TE_MULTILINE, size=(-1,295))
    hBox3.Add(urlFld, 1, flag=wx.EXPAND)
    vBox.Add(hBox3, flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=10)


    panel.SetSizer(vBox)

#GUI EVENTS
def checkBtnClick(self, e):
    urlFld.SetValue(self, "blahh")

#MENU ITEM EVENTS
def OnAbout(self,e):
    dlg = wx.MessageDialog(self, "A small text editor", "My test editor", wx.OK)  #create a dialog (dlg) box to display the message, and ok button
    dlg.ShowModal()  #show the dialog box, modal means cannot do anything on the program until clicks ok or cancel
    dlg.Destroy()  #destroy the dialog box when its not needed

def OnExit(self,e):
    self.Close(True)  #on menu item select, close the app frame.

def OnOpen(self,e):
    self.dirname=""  #set directory name to blank
    dlg = wx.FileDialog(self, "Choose a file to open", self.dirname, "", "*.*", wx.OPEN) #open the dialog boxto open file
    if dlg.ShowModal() == wx.ID_OK:  #if positive button selected....
        self.filename = dlg.GetFilename()  #get the filename of the file
        self.dirname = dlg.GetDirectory()  #get the directory of where file is located
        f = open(os.path.join(self.dirname, self.filename), 'r')  #traverse the file directory and find filename in the OS
        text = f.read()
        self.urlFld.SetValue(f.read())  #open the file from location as read
        self.urlFld.WriteText(text)
        f.close
    dlg.Destroy()

app = wx.App(False)   #creates a new app
MainWindow(None, "URL Checker")  #give the frame a title
app.MainLoop()  #start the apps mainloop which handles app events

谢谢

【问题讨论】:

    标签: wxpython


    【解决方案1】:

    urlFld 应该是类的一个属性:

    # 'self' added
    self.urlFld = wx.TextCtrl(panel, style=wx.TE_MULTILINE, size=(-1,295))
    

    而不是局部变量,以便您可以在方法之外引用它。

    【讨论】:

    • 这是有道理的。效果很好,非常感谢:)
    • 出于兴趣,我应该使用什么作为最佳实践? SetValue(f.read) 或 WriteText(text)??
    • 查看我的post方法file_open中的代码,它使用self.urlFld.LoadFile
    • 你的版本和我的版本有什么区别,比如,为什么你做的不一样,为什么这样更好?
    • 我正在使用 with 打开对话框,因此无需销毁它,它在完成后会自动执行此操作,并且我知道如何通过尝试不同的东西来设置您刚刚猜测的文件中的文本.
    【解决方案2】:

    不要使用全局变量,使用 self 代替这里是修改后的代码

    import wx
    import os
    
    
    
    class MainWindow(wx.Frame):
        def __init__(self, parent, title):
            self.dirname = ''
            super(MainWindow, self).__init__(parent, title=title, size=(450, 450))
            self.CreateStatusBar()  # A Statusbar in the bottom of the window
    
            self.InitGUI()
            self.Centre()
            self.Show()
    
        def InitGUI(self):
    
            # MENUS
            fileMenu = wx.Menu()  # create menu for file
            viewMenu = wx.Menu()  # create a menu for view
            helpMenu = wx.Menu()  # create a menu for help
    
            # FILE MENU
            menuOpen = fileMenu.Append(wx.ID_OPEN,
                            "&Open", " Open a file to edit")  # add open to File
            menuExit = fileMenu.Append(wx.ID_EXIT, "E&xit",
                                    " Terminate the program")  # add exit to File
    
            # VIEW MENU
            menuView = viewMenu.Append(wx.ID_ANY, "TODO:", "Still to do")
    
            # HELP MENU
            menuAbout = helpMenu.Append(wx.ID_ABOUT, "&About",
                                    "About this program")  # add about menu item
    
            # MENUBAR
            menuBar = wx.MenuBar()
            menuBar.Append(fileMenu, "&File")  # Adding the "filemenu" to the MenuBar
            menuBar.Append(viewMenu, "&View")
            menuBar.Append(helpMenu, "&Help")
            self.SetMenuBar(menuBar)  # Adding the MenuBar to the Frame content.
    
            '''#TOOLBAR
            toolbar = self.CreateToolBar()
            toolOpen = toolbar.AddLabelTool(wx.ID_OPEN, "Open", wx.Bitmap("open.png"))
            toolExit = toolbar.AddLabelTool(wx.ID_EXIT, "Exit", wx.Bitmap("blah.png"))'''
    
            # MENU EVENTS
            self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
            self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
            self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
    
            '''#TOOLBAR EVENTS
            self.Bind(wx.EVT_TOOL, self.OnExit, toolExit)
            self.Bind(wx.EVT_TOOL, self.OnOpen, toolOpen)'''
    
    
            # PANEL
            panel = wx.Panel(self)
    
            panel.SetBackgroundColour('#ededed')
            vBox = wx.BoxSizer(wx.VERTICAL)
    
            hBox = wx.BoxSizer(wx.HORIZONTAL)
            hBox.Add(wx.StaticText(panel, label="File:"), flag=wx.TOP, border=3)
            hBox.Add(wx.TextCtrl(panel), 1, flag=wx.LEFT, border=10)
            checkBtn = wx.Button(panel, -1, "Check")
            self.Bind(wx.EVT_BUTTON, self.checkBtnClick)
            hBox.Add(checkBtn, 0, flag=wx.LEFT, border=10)
            vBox.Add(hBox, flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, border=10)
            vBox.Add((-1, 10))
    
            hBox2 = wx.BoxSizer(wx.HORIZONTAL)
            hBox2.Add(wx.StaticText(panel, label="URLs:"))
            vBox.Add(hBox2, flag=wx.LEFT, border=10)
            vBox.Add((-1, 5))
    
            hBox3 = wx.BoxSizer(wx.HORIZONTAL)
            self.urlFld = wx.TextCtrl(panel, style=wx.TE_MULTILINE, size=(-1, 295))
            hBox3.Add(self.urlFld, 1, flag=wx.EXPAND)
            vBox.Add(hBox3, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=10)
    
    
            panel.SetSizer(vBox)
    
        # GUI EVENTS
        def checkBtnClick(self, e):
            self.urlFld.SetValue("blahh")
    
        # MENU ITEM EVENTS
        def OnAbout(self, e):
            dlg = wx.MessageDialog(self, "A small text editor",
                                   "My test editor", wx.OK)  # create a dialog (dlg) box to display the message, and ok button
            dlg.ShowModal()  # show the dialog box, modal means cannot do anything on the program until clicks ok or cancel
            dlg.Destroy()  # destroy the dialog box when its not needed
    
        def OnExit(self, e):
            self.Close(True)  # on menu item select, close the app frame.
    
        def OnOpen(self, e):
            self.file_open()
            e.Skip()
    
        def file_open(self):  # 9
            with wx.FileDialog(self, "Choose a file to open", self.dirname,
                               "", "*.*", wx.OPEN) as dlg:
                if dlg.ShowModal() == wx.ID_OK:
                    directory, filename = dlg.GetDirectory(), dlg.GetFilename()
                    self.urlFld.LoadFile('/'.join((directory, filename)))
                    self.SetTitle(filename)
    
    app = wx.App(False)  # creates a new app
    MainWindow(None, "URL Checker")  # give the frame a title
    app.MainLoop()  # start the apps mainloop which handles app events
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-15
      • 2010-11-17
      • 2016-09-07
      • 2013-09-14
      • 1970-01-01
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多