wxPython能否管理按钮悬停颜色?适配深色主题开发需求
解决wxPython深色主题下按钮自定义悬停颜色的问题
原生wx.Button的悬停样式受系统或内置主题控制,直接通过EVT_ENTER_WINDOW/EVT_LEAVE_WINDOW修改背景色不会生效——因为控件会自动重绘原生样式。以下两种方案可实现自定义悬停颜色:
方案一:重载按钮的绘制逻辑
完全接管按钮的绘制过程,手动控制正常和悬停状态的样式:
import wx class AppButton(wx.Button): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.SetLabel('Test') self.normal_bg = '#131313' self.hover_bg = '#2a2a2a' self.fg_color = 'white' self.SetOwnBackgroundColour(self.normal_bg) self.SetOwnForegroundColour(self.fg_color) self.SetPosition((100,100)) self.is_hover = False self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnter) self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave) self.Bind(wx.EVT_PAINT, self.OnPaint) def OnEnter(self, event): self.is_hover = True self.Refresh() event.Skip() def OnLeave(self, event): self.is_hover = False self.Refresh() event.Skip() def OnPaint(self, event): dc = wx.PaintDC(self) rect = self.GetClientRect() bg_color = self.hover_bg if self.is_hover else self.normal_bg dc.SetBrush(wx.Brush(bg_color)) dc.SetPen(wx.Pen(bg_color)) dc.DrawRectangle(rect) dc.SetTextForeground(self.fg_color) dc.DrawLabel(self.GetLabel(), rect, wx.ALIGN_CENTER) class Example(wx.Frame): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.SetSize(300,300) self.SetBackgroundColour('#151719') self.Center() self.initUI() def initUI(self): panel = wx.Panel(self) self.button = AppButton(panel) if __name__ == '__main__': app = wx.App() ex = Example(None) ex.Show() app.MainLoop()
方案二:使用wx.lib.buttons的GenButton
GenButton是纯Python实现的按钮控件,支持直接设置悬停属性,无需手动处理绘制:
import wx from wx.lib.buttons import GenButton class AppButton(GenButton): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.SetLabel('Test') self.SetBackgroundColour('#131313') self.SetForegroundColour('white') # 直接设置悬停样式 self.hoverBackground = '#2a2a2a' self.hoverForeground = 'white' self.SetPosition((100,100)) self.SetUseFocusIndicator(False) # 可选,移除默认焦点框 class Example(wx.Frame): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.SetSize(300,300) self.SetBackgroundColour('#151719') self.Center() self.initUI() def initUI(self): panel = wx.Panel(self) self.button = AppButton(panel) if __name__ == '__main__': app = wx.App() ex = Example(None) ex.Show() app.MainLoop()
内容的提问来源于stack exchange,提问作者Juicy Apricot
相关产品推荐
相关产品推荐

