将打印输出重定向到状态栏
有没有办法把文字显示到状态栏?我想在状态栏上打印一些信息。
我想要的效果是这样的,但现在不行:
import sys
import wx
class RedirectText:
def __init__(self, statusbar):
self.statusbar = statusbar
def write(self,string):
self.statusbar.SetStatusText(string)
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.log = wx.TextCtrl(self, -1, '', style=wx.TE_READONLY|wx.TE_MULTILINE)
sizer = wx.BoxSizer()
sizer.Add(self.log, 1, wx.ALL | wx.EXPAND, 5)
self.SetSizer(sizer)
self.statusbar = self.CreateStatusBar()
redirection = RedirectText(self.statusbar)
sys.stdout = redirection
print 'hello'
self.Bind(wx.EVT_CLOSE, self.OnClose)
def OnClose(self, event):
raise RuntimeError('error')
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MainFrame()
frame.Show()
app.MainLoop()
谢谢
2 个回答
0
@jro说得对。print
这个命令实际上是把"hello\n"
分成两次通过标准输出发送的。
还有一个更简单的解决办法(虽然可能不太方便),就是在你的print
语句后面加一个逗号:
print 'hello',
这样做有效,因为逗号告诉print
要在同一行继续输出。
3
这可能有点出乎意料,但你定义的 write
函数在你现在的代码中会被调用两次:第一次它会接收到 "hello" 这个字符串,然后是一个换行符。因为换行符在你的状态栏中看不见,所以看起来好像没有任何更新。
一个简单的解决办法是检查一下你在 write
函数中的 string
内容,看看里面是否有数据:
def write(self, string):
string = string.strip()
if len(string) > 0:
self.statusbar.SetStatusText(string)