Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me
Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old October 27th, 2004, 03:40 PM
Tkinter_Bell Tkinter_Bell is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Oct 2004
Location: Isle of dogs
Posts: 68 Tkinter_Bell User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 5
Smile Migrating to wxPython from TKinter

Interested in wxPython but I cannot find what I need concerning text highlighting or changing the colour of a word. You know! something like syntax highlighting

If anyone can give me a simple Hello World application that uses a simple regular expression, like searching the wxStyledTextCtrl for any occurrences of Hello then highlight it blue and any occurrence of World and highlight it red.

Or if you don't want to sweet it out for me, show me the wxStyledTextCtrol methods that are responsible for text highlighting and might show compatibility with regular expressions.

For Tkinter I use a small loop. 'compile' equals the regular expression mystring equals string to be searched, in this case its a string from Tkinters Textwidget itself.

self.iterator = re.finditer(compile,mystring)
for match in self.iterator:
highlight(self.editor,match,hit)

#func Strap this baby to a Textwidget first
def config_tags(text):
btags = text.bindtags()
text.bindtags(btags[1:] + btags[:1])
text.tag_configure("hit",foreground="blue")
text.tag_configure("hit1",foreground="red")

#func highlights text widget based on regular expression match and a hit
def highlight_all_text(text,match,hit):
if match:
regs = match.span()# regular expression, you know this
first, last = regs
pfirst = "1.0 + %d chars" % first
plast = "1.0 + %d chars" % last
text.tag_add(hit, pfirst, plast)# The magic happens here.
text.yview_pickplace(pfirst)


Reply With Quote
  #2  
Old October 27th, 2004, 09:21 PM
rebbit rebbit is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Jan 2004
Posts: 84 rebbit User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 8 h 7 m
Reputation Power: 5
I seem to recall that wxPython actually has a syntax highlighting widget as a standard. I dunno, I never used wxPython much, but that is one thing I remember. I'm not 100% sure on it though.

Reply With Quote
  #3  
Old October 28th, 2004, 06:17 PM
Grim Archon's Avatar
Grim Archon Grim Archon is offline
Mini me.
Dev Shed Novice (500 - 999 posts)
 
Join Date: Nov 2003
Location: Cambridge, UK
Posts: 783 Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)  Folding Points: 1488 Folding Title: Novice Folder
Time spent in forums: 3 Days 2 h 15 m 57 sec
Reputation Power: 8
Send a message via MSN to Grim Archon
wxStyledTextCtrl already has the ability to understand HTML type tags if you tell it to use an HTML lexer. The underlying scintilla core already supports many languages. All you have to do is tell it what language you are editing and what colour etc. you want tokens to be displayed with. It does the rest!

So:
1. Create a parent widget to hold the text widget
2. Define a lexer
3. Create the text widget and let it know what lexer to use
4. Define the colour font etc for each (predefined by Scintilla) token.
5. Copy the text into the widget with SetText()
6. Let the user edit it!

Here are some key code fragments to give you a flavour.
Code:
from wxPython.stc import *
class Custom:
    #
    def __init__(self):
        self.defaultTabWidth = 4
        self.useTabs = 0
        self.lexerId = wxSTC_LEX_NULL
        self.rightMargin = 68
        self.breakChars = ' \t.,/\\<>?!@#$%^&*(){}[]+\'"'
    def getLexerId(self):
        return self.lexerId
    def getDefaultTabWidth(self):
        return self.defaultTabWidth
    def getUseTabs(self):
        return self.useTabs
    def getRightMargin(self):
        return self.rightMargin
    def getBreakChars(self):
        return self.breakChars
    def do_auto_indent(self, buffer, usingTabs, currentTabWidth):
        return 1

class HtmlCustom(Custom):
    def __init__(self):
        Custom.__init__(self)
        self.defaultTabWidth = 4
        self.useTabs = 0
        self.lexerId = wxSTC_LEX_HTML
......
And in the main class we have
        self.Text = wxStyledTextCtrl(id=wxID_WXFRAME1TEXT, name='Text',
              parent=self.mainwindow, pos=wxPoint(0, 0), size=wxSize(623, 350),
              style=0)
......

        self.fileCustom = HtmlCustom()
        self.Text.StyleSetSpec(wxSTC_STYLE_DEFAULT, "size:%d,face:%s" % (pb, face3))
        self.Text.StyleSetSpec(wxSTC_H_TAG, "size:%d,bold,face:%s,fore:#0000FF" % (pb+2, face1))
        self.Text.StyleSetSpec(wxSTC_H_TAGUNKNOWN, "face:%s,italic,fore:#FF0000,size:%d" % (face2, pb))
        self.Text.StyleSetSpec(wxSTC_H_ATTRIBUTE, "face:%s,bold,size:%d" % (face2, pb+2))
        self.Text.StyleSetSpec(wxSTC_H_ATTRIBUTEUNKNOWN, "face:%s,size:%d" % (face1, pb-1))
        self.Text.StyleSetSpec(wxSTC_H_COMMENT, "face:%s,size:%d,back:#ffff00" % (face1, pb-1))
        self.Text.StyleSetSpec(wxSTC_H_SCRIPT, "face:%s,size:%d" % (face1, pb-1))

        self.Text.SetUseTabs(self.fileCustom.getUseTabs())
        self.Text.currentTabWidth = self.fileCustom.getDefaultTabWidth()
        self.Text.SetTabWidth(self.fileCustom.getDefaultTabWidth())
        lexerId = self.fileCustom.getLexerId()
        self.Text.SetLexer(lexerId)
        self.Text.SetWrapMode(wxSTC_WRAP_WORD)

I don't claim credit for the Custom class but you should see it is useful if you ever want your editor to display other code.

The wxPython and wxWindows docs should take you further.
http://wiki.wxpython.org/index.cgi/wxStyledTextCtrl
If you need further info I suggest you look at the source code for the editors supplied with wxPython - it helped me.

grim
__________________
*** Experimental Python Markup CGI V2 ***

Last edited by Grim Archon : October 28th, 2004 at 06:21 PM.

Reply With Quote
  #4  
Old October 29th, 2004, 09:12 AM
Tkinter_Bell Tkinter_Bell is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Oct 2004
Location: Isle of dogs
Posts: 68 Tkinter_Bell User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 5
If what you say is true, most of my problems are gone, I wouldn't even need that o'riellly book on regular expressions that a bought last week. I did try the example but it require globel veriables that I did not have.

I have been trying to find some useful documention on wxStyledTextCtrl. And it is virtually non excistent or comprised of a little more then a half baked Java doc style file with a long list of methods and function with one line comments.

Reply With Quote
  #5  
Old October 29th, 2004, 10:38 AM
Grim Archon's Avatar
Grim Archon Grim Archon is offline
Mini me.
Dev Shed Novice (500 - 999 posts)
 
Join Date: Nov 2003
Location: Cambridge, UK
Posts: 783 Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)  Folding Points: 1488 Folding Title: Novice Folder
Time spent in forums: 3 Days 2 h 15 m 57 sec
Reputation Power: 8
Send a message via MSN to Grim Archon
I didn't supply the full code, as I said it was just fragments. It didn't take 5 mins to write and is to some extent is work in progress

I used the documentation that is supplied with boa constructor:
http://sourceforge.net/project/showfiles.php?group_id=1909&package_id=1856&release_id=261502
The wxPython doc is where the stc component is described.

grim

Reply With Quote
  #6  
Old October 30th, 2004, 03:05 AM
Grim Archon's Avatar
Grim Archon Grim Archon is offline
Mini me.
Dev Shed Novice (500 - 999 posts)
 
Join Date: Nov 2003
Location: Cambridge, UK
Posts: 783 Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)Grim Archon User rank is Corporal (100 - 500 Reputation Level)  Folding Points: 1488 Folding Title: Novice Folder
Time spent in forums: 3 Days 2 h 15 m 57 sec
Reputation Power: 8
Send a message via MSN to Grim Archon
I just upgraded my Boa installation and found that using the control is much easier these days. So here is a quick sample based on the documentation supplied with Boa and self contained (you only need wxPython to run it).
Code:
#Boa:Frame:wxFrame1

from wxPython.wx import *
from wxPython.lib.anchors import LayoutAnchors
from wxPython.stc import *
htmlKeywords = '''a abbr acronym address applet area b base basefont bdo big blockquote
         body br button caption center cite code col colgroup dd del dfn dir
         div dl dt em fieldset font form frame frameset h1 h2 h3 h4 h5 h6
         head hr html i iframe img input ins isindex kbd label legend li link
         map menu meta noframes noscript object ol optgroup option p param
         pre q s samp script select small span strike strong style sub sup
         table tbody td textarea tfoot th thead title tr tt u ul var xml
         xmlns abbr accept-charset accept accesskey action align alink alt
         archive axis background bgcolor border cellpadding cellspacing char
         charoff charset checked cite class classid clear codebase codetype
         color cols colspan compact content coords data datafld dataformatas
         datapagesize datasrc datetime declare defer dir disabled enctype
         event face for frame frameborder headers height href hreflang hspace
         http-equiv id ismap label lang language leftmargin link longdesc
         marginwidth marginheight maxlength media method multiple name nohref
         noresize noshade nowrap object onblur onchange onclick ondblclick
         onfocus onkeydown onkeypress onkeyup onload onmousedown onmousemove
         onmouseover onmouseout onmouseup onreset onselect onsubmit onunload
         profile prompt readonly rel rev rows rowspan rules scheme scope
         selected shape size span src standby start style summary tabindex
         target text title topmargin type usemap valign value valuetype
         version vlink vspace width text password checkbox radio submit reset
         file hidden image public !doctype'''


def create(parent):
    return wxFrame1(parent)

[wxID_WXFRAME1, wxID_WXFRAME1STYLEDTEXTCTRL1,
] = map(lambda _init_ctrls: wxNewId(), range(2))

class wxFrame1(wxFrame):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wxFrame.__init__(self, id=wxID_WXFRAME1, name='', parent=prnt,
              pos=wxPoint(496, 283), size=wxSize(610, 522),
              style=wxDEFAULT_FRAME_STYLE, title='wxFrame1')
        self.SetClientSize(wxSize(602, 488))

        self.styledTextCtrl1 = wxStyledTextCtrl(id=wxID_WXFRAME1STYLEDTEXTCTRL1,
              name='styledTextCtrl1', parent=self, pos=wxPoint(0, 0),
              size=wxSize(602, 488), style=0)
        self.styledTextCtrl1.SetLexer(wxSTC_LEX_HTML)
        self.styledTextCtrl1.Show(True)
        self.styledTextCtrl1.SetConstraints(LayoutAnchors(self.styledTextCtrl1,
              True, True, False, False))
        self.styledTextCtrl1.SetViewEOL(True)

    def __init__(self, parent):
        self._init_ctrls(parent)
        self.styledTextCtrl1.StyleSetSpec(wxSTC_H_TAG, "size:%d,bold,face:%s,fore:#0000FF" % (26, 'Arial'))
        self.styledTextCtrl1.StyleSetSpec(wxSTC_H_ATTRIBUTE, "size:%d,bold,face:%s,fore:#DD00FF" % (16, 'Arial'))
        self.styledTextCtrl1.StyleSetSpec(wxSTC_H_ATTRIBUTEUNKNOWN, "size:%d,bold,face:%s,fore:#FFEE00" % (26, 'Arial'))
        self.styledTextCtrl1.SetKeyWords(0,htmlKeywords)
        self.styledTextCtrl1.SetText('''<h1 color="red" bad_attrib="ahha">hello cruel world</h1>''')



class BoaApp(wxApp):
    def OnInit(self):
        wxInitAllImageHandlers()
        self.main = create(None)
        self.main.Show()
        self.SetTopWindow(self.main)
        return True

def main():
    application = BoaApp(0)
    application.MainLoop()

if __name__ == '__main__':
    main()

grim

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > Migrating to wxPython from TKinter


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump


Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 





© 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
Stay green...Green IT