Question

I was looking for a way to transform text entered into the textctrl field to uppercase. I tried using a validator and transforming the value of the key event object to the uppercase letter char value using 'ord' however I could not find any 'set' methods. I may be able to access the event class variable directly as class variables in python are never really private but im having trouble finding the exact information I need to do that.

Anyway this seems like an overly complicated approach. Does anyone else have any suggestions. Am I missing something obvious?

Was it helpful?

Solution

Try this.

import wx

class UpperTextCtrl(wx.TextCtrl):
    def __init__(self, *args, **kwargs):
        super(UpperTextCtrl, self).__init__(*args, **kwargs)
        self.Bind(wx.EVT_TEXT, self.on_text)
    def on_text(self, event):
        event.Skip()
        selection = self.GetSelection()
        value = self.GetValue().upper()
        self.ChangeValue(value)
        self.SetSelection(*selection)

class Frame(wx.Frame):
    def __init__(self):
        super(Frame, self).__init__(None, -1, 'Uppercase Text Control')
        panel = wx.Panel(self, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        text = UpperTextCtrl(panel, -1, style=wx.TE_MULTILINE)

        # change the font
        font = text.GetFont()
        font.SetPointSize(12)
        text.SetFont(font)

        sizer.Add(text, 1, wx.EXPAND|wx.ALL, 10)
        panel.SetSizer(sizer)

if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = Frame()
    frame.Show()
    app.MainLoop()

OTHER TIPS

Check this solution.

import wx
import string

class UpperTextCtrl(wx.TextCtrl):
    def __init__(self, *args, **kwargs):
        super(UpperTextCtrl, self).__init__(*args, **kwargs)
        self.Bind(wx.EVT_CHAR, self.on_char)
    def on_char(self, event):
        key=event.GetKeyCode()
        text_ctrl=event.GetEventObject()
        if chr(key) in string.letters:
            text_ctrl.AppendText(chr(key).upper())
            return
        event.Skip()

class Frame(wx.Frame):
    def __init__(self):
        super(Frame, self).__init__(None, -1, 'Uppercase Text Control')
        panel = wx.Panel(self, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        text = UpperTextCtrl(panel, -1, style=wx.TE_MULTILINE)

        # change the font
        font = text.GetFont()
        font.SetPointSize(12)
        text.SetFont(font)

        sizer.Add(text, 1, wx.EXPAND|wx.ALL, 10)
        panel.SetSizer(sizer)

if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = Frame()
    frame.Show()
    app.MainLoop()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top