Search code examples
pythonwindowspython-2.7wxpythonwxwidgets

wx Python - colour coding - StyledTextctrl


My Problem:

Hi! i have been googling for 2 days right now, and i have not found an answer yet :( what am i trying to do is when i type a keyword(e.g "True" and "False") that word would turn red

i am currently imported this module:

import wx
import wx.stc
import os, sys

I have tried:

i have tried code from here: Here but that does not do "some" keyword but "all" word next to it

Screenshot:

Any Help Would Be Very Appreciated


Solution

  • First derive a class which is a subclass of wxStyledTextCtrl

    class Script:public wxStyledTextCtrl
    

    The following code is for Lua, but the same logic is applicable to any language. So you will need to modify it for Python and add the code to your constructor.

    SetLexer(wxSTC_LEX_LUA); //Dont forget to set the lexer to Python
    m_LuaKeywords =_T("and break do else elseif end false for function if in local nil not or repeat return then true until while pairs ipairs");     
    SetWordChars(wxT("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMONPQRSTUVWXYZ._") );
    SetKeyWords(0,m_LuaKeywords);
    SetFont(font);
    
    StyleSetForeground(0,  wxColour(128, 128, 128)); // White space
    StyleSetForeground(wxSTC_LUA_COMMENT,  wxColour(0,   127, 0));   // Block Comment
    font.SetPointSize(10); font.Italic();
    StyleSetFont(wxSTC_LUA_COMMENT, font);
    StyleSetUnderline(wxSTC_LUA_COMMENT, false);
    
    StyleSetForeground(wxSTC_LUA_COMMENTLINE, wxColour(0,   127, 0));   //Line Comment
    StyleSetFont(wxSTC_LUA_COMMENTLINE,font);    //doc. Comment
    StyleSetUnderline(wxSTC_LUA_COMMENTLINE, false);
    
    font.SetPointSize(11);font.SetStyle(wxFONTSTYLE_NORMAL);
    StyleSetForeground(wxSTC_LUA_NUMBER, wxColour(127, 127, 127)); // Number
    StyleSetFont(wxSTC_LUA_NUMBER, font);
    
    StyleSetForeground(wxSTC_LUA_STRING, wxColour(0,   0,   127)); // Double quoted string
    StyleSetBold(wxSTC_LUA_STRING,  true);
    StyleSetUnderline(wxSTC_LUA_STRING, false);
    

    If you look at wx/stc/stc.h, you will see that the states for Python are as follows:

    /// Lexical states for SCLEX_PYTHON
    #define wxSTC_P_DEFAULT 0
    #define wxSTC_P_COMMENTLINE 1
    #define wxSTC_P_NUMBER 2
    #define wxSTC_P_STRING 3
    #define wxSTC_P_CHARACTER 4
    #define wxSTC_P_WORD 5
    #define wxSTC_P_TRIPLE 6
    #define wxSTC_P_TRIPLEDOUBLE 7
    #define wxSTC_P_CLASSNAME 8
    #define wxSTC_P_DEFNAME 9
    #define wxSTC_P_OPERATOR 10
    #define wxSTC_P_IDENTIFIER 11
    #define wxSTC_P_COMMENTBLOCK 12
    #define wxSTC_P_STRINGEOL 13
    #define wxSTC_P_WORD2 14
    #define wxSTC_P_DECORATOR 15