How to make something like a log box in wxPython

a 夏天 提交于 2019-12-22 05:57:13

问题


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?


回答1:


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/




回答2:


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



来源:https://stackoverflow.com/questions/5493984/how-to-make-something-like-a-log-box-in-wxpython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!