How to make something like a log box in wxPython

2019-04-29 15:39发布

I'm assuming this is possible with a multiline text box, but not sure how to do it. What I'm looking to do is make a log box in my wxPython program, where I can write messages to it when certain actions happen. Also, i need to write the messages not only when an event happens, but certain times in the code. How would i get it to redraw the window so the messages appear at that instant?

2条回答
狗以群分
2楼-- · 2019-04-29 15:57

I wrote an article on this sort of thing a couple years ago:

http://www.blog.pythonlibrary.org/2009/01/01/wxpython-redirecting-stdout-stderr/

查看更多
Luminary・发光体
3楼-- · 2019-04-29 16:01

If you would like just a log dialog in wxpython, use wx.LogWindow:

import wx

class MainWindow(wx.Frame):

    def __init__(self, parent=None):
        wx.Frame.__init__(self, parent, wx.NewId(), 'Logging')

        self.log_window = wx.LogWindow(self, 'Log Window', bShow=True)

        box_sizer = wx.BoxSizer(orient=wx.VERTICAL)        
        show_log_button = wx.Button(self, wx.NewId(), 'Show Log')
        show_log_button.Bind(wx.EVT_BUTTON, self._show_log)        

        log_message_button = wx.Button(self, wx.NewId(), 'Log Message')
        log_message_button.Bind(wx.EVT_BUTTON, self._log_message)

        box_sizer.AddMany((show_log_button, log_message_button))
        self.SetSizer(box_sizer)
        self.Fit()

        self.Bind(wx.EVT_CLOSE, self._on_close)

    def _show_log(self, event):
        self.log_window.Show()

    def _log_message(self, event):
        wx.LogError('New error message')

    def _on_close(self, event):
        self.log_window.this.disown()
        wx.Log.SetActiveTarget(None)
        event.Skip()

if __name__ == '__main__':
    app = wx.PySimpleApp()
    dlg = MainWindow()
    dlg.Show()
    app.MainLoop()

Where bShow in wx.LogWindow is if it's initially shown or not. This will log nicely all your wx.LogX messages that you can trigger, and it still passes it on to any other handlers.

Another method you could use would be to log with python and then, upon opening a frame/window with a text control in it, use LoadFile to open the log file:

import logging
LOG_FILENAME = 'example.log'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)

logging.debug('This message should go to the log file')

Then, when creating a wx.TextCtrl somewhere:

log_control = wx.TextCtrl(self, wx.NewId(), style=wx.TE_MULTILINE|wx.TE_READONLY)
log_control.LoadFile('example.log')

EDIT: This now works with the _on_close event! Thanks Fenikso

查看更多
登录 后发表回答