在我的GUI中,我使用TextCtrls作为用户输入。该工具指导用户执行一些步骤,在这些步骤中必须输入不同的输入。因此,如果TextCtrl是强制性的但为空,那么我想在许多带有红色边框的工具和网站上将它们突出显示为常见。
经过一番研究,我注意到如果不创建一个自定义小部件,这是不可能的。

那么,除了改变背景颜色以外,是否有某种“标准”方式可以突出显示它?

如果有人需要测试的最小示例:

import wx

class Example(wx.Frame):

    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw)

        self.InitUI()

    def InitUI(self):
        pnl = wx.Panel(self)
        test_text_ctrl = wx.TextCtrl(pnl)

        self.SetSize((350, 250))
        self.Centre()

def main():
    app = wx.App()
    ex = Example(None)
    ex.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

最佳答案

我的本机解决方案是将每个textctrl放在可以着色的自己的面板上。这将在每个textctrl周围产生边框的错觉。这是一个例子:

import wx, traceback

# sets the width of the highlight border
HIGHLIGHT_WIDTH = 2
HIGHLIGHT_COLOR = (255, 0, 0)


class Mainframe(wx.Frame):

    def __init__(self, parent=None):
        self.bg_color = wx.SystemSettings.GetColour(wx.SYS_COLOUR_MENU)
        self.highligt_color = wx.Colour(HIGHLIGHT_COLOR)

        wx.Frame.__init__(self, parent, id=wx.ID_ANY, title="Highlight TextCtrl Test", size=wx.Size(500, 300),
                          style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)
        self.SetBackgroundColour(self.bg_color)

        main_sizer = wx.BoxSizer(wx.VERTICAL)

        self.textctrl_panel = wx.Panel(self)
        self.textctrl_panel.SetBackgroundColour(self.highligt_color)

        textctrl_panel_sizer = wx.BoxSizer(wx.VERTICAL)

        self.textctrl = wx.TextCtrl(self.textctrl_panel)
        textctrl_panel_sizer.Add(self.textctrl, 0, wx.ALL, HIGHLIGHT_WIDTH)

        self.textctrl_panel.SetSizer(textctrl_panel_sizer)
        self.textctrl_panel.Layout()
        textctrl_panel_sizer.Fit(self.textctrl_panel)
        main_sizer.Add(self.textctrl_panel, 0, wx.ALIGN_CENTER_HORIZONTAL, 5)

        self.SetSizer(main_sizer)
        self.Layout()

        self.Centre(wx.BOTH)

        self.textctrl.Bind(wx.EVT_TEXT, self.on_text)

        # to reduce flickering
        self.SetDoubleBuffered(True)
        self.CenterOnScreen(wx.BOTH)
        self.Show()

    def on_text(self, event):
        """ triggered every time the text ctrl text is updated, schedules validate_text() to run after the event """
        event.Skip()
        wx.CallAfter(self.validate_text)

    def validate_text(self):
        """ sets the textctrl panel background color to give the appearance
        of a red highlight if there is no text in the text ctrl """
        color = self.bg_color if self.textctrl.GetValue() else self.highligt_color
        self.textctrl_panel.SetBackgroundColour(color)
        # force the window to repaint
        self.textctrl_panel.Refresh()


try:

    app = wx.App()
    frame = Mainframe()
    app.MainLoop()
except:
    input(traceback.format_exc())

关于python - wxPython-如何“突出显示” TextCtrl?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57993241/

10-12 16:58