使用wxPython更改工具栏中的标签

1 投票
2 回答
1573 浏览
提问于 2025-04-16 07:49

我现在在wxpython中有一个工具栏,上面有一个开始的图标。我想要的是,当点击这个图标时,它的图标和使用的方法都能变成停止的状态。

这是我目前写的代码:

#!/usr/bin/env python
# encoding: utf-8
"""
logClient2.py    
Created by Allister on 2010-11-30.
"""

import wx
import sqlite3

WINDOW_SIZE = (900,400)

class logClient(wx.Frame):
    def __init__(self, parent, id, title):

        wx.Frame.__init__(self, parent, id, title, size=WINDOW_SIZE)        

        self.toolbar = self.CreateToolBar()
        self.toolbar.AddLabelTool(1, 'Refresh', wx.Bitmap('icons/refresh_icon.png'))
        self.toolbar.Realize()

        self.Bind(wx.EVT_TOOL, self.startLiveUpdate, id=1)

        self.Show(True)

    def startLiveUpdate(self, event):
      pass  


if __name__ == '__main__':
    app = wx.App(False)
    logClient(None, -1, "Log Event Viewer")
    app.MainLoop()

我不太确定在startLiveUpdate方法里该写些什么?

谢谢大家的帮助!

2 个回答

1

这里有一个比被接受的答案更简单的版本,适用于wxpython 4.x。

self.tool = self.toolbar.AddTool(-1, "A tool", "image.png")

...

def change_tool_label(self):
    self.tool.SetLabel("A new label")
    # need to call Realize() to re-draw the toolbar
    self.toolbar.Realize()
2

这是一个快速拼凑出来的代码。已经在Ubuntu 9.10、Python 2.6和wx 2.8.10.1上测试过了。

#!/usr/bin/env python
# encoding: utf-8
"""
logClient2.py    
Created by Allister on 2010-11-30.
"""

import wx
import sqlite3

WINDOW_SIZE = (900,400)

class logClient(wx.Frame):
    def __init__(self, parent, id, title):

        wx.Frame.__init__(self, parent, id, title, size=WINDOW_SIZE)        

        self.toolbar = self.CreateToolBar()
        self.startLiveUpdate(None)

        self.Show(True)

    def startLiveUpdate(self, event):
        self.createToolbarItem("Refresh", "refresh.jpg", self.stopLiveUpdate)

    def stopLiveUpdate(self, event):
        self.createToolbarItem("Stop", "refresh2.jpg", self.startLiveUpdate)


    def createToolbarItem(self, label, imageName, method):
        self.toolbar.RemoveTool(1)
        self.toolbar.AddLabelTool(1, label, wx.Bitmap(imageName))
        self.toolbar.Realize()
        self.Bind(wx.EVT_TOOL, method, id=1)


if __name__ == '__main__':
    app = wx.App(False)
    logClient(None, -1, "Log Event Viewer")
    app.MainLoop()

撰写回答