Search code examples
pythonwxpython

Mouse events on text in Python using wxPython


This is what I am trying to do:

I create a window and there is text that is displayed on it, as a user I click on the text, example: the displayed text is.

'Hello World, I am a Python program.'

So if the user clicks words, I want it to generate an event and it would go into a function and I want to do something in the function (like changing the color of that word, so I also need to track which word I clicked)

I am not so sure how to do that, I could potentially make each word a button but that would be ugly.


Solution

  • import wx
    def SomeListener(evt):
        print "Got Event:",evt
        print "My XY:",evt.GetX(),evt.GetY()
        #youll have to figure out which word you clicked using x,y (note x,y relative to static text field)
    a= wx.App(redirect=False)
    f = wx.Frame(None,-1)
    p = wx.Panel(f,-1)
    t = wx.StaticText(p,-1,"Some Text")
    t.Bind(wx.EVT_LEFT_DOWN,SomeListener)
    f.Show()
    a.MainLoop()
    

    or using htmlwin ... but it underlines all the words... I wasnt able to figure out how to not do that

    import wx
    
    import wx.html
    def OnClickWord(e):
        print "You Clicked:",e.GetLinkInfo().GetHref()
        return
    class MyHtmlFrame(wx.Frame):
    
        def __init__(self, parent, title):
    
            wx.Frame.__init__(self, parent, -1, title)
    
            html = wx.html.HtmlWindow(self)
    
            #if "gtk2" in wx.PlatformInfo:
    
            html.SetStandardFonts()
    
            html.SetPage(
            "<style>a {text-decoration: none;color: #000; }</style>" #sorry no css support :/
            "<a href=\"word1\">Word1</a> <a href=\"word2\">word 2</a> <a href=\"wizard of oz\">wizard of oz</a>.")
    
    app = wx.PySimpleApp()
    
    frm = MyHtmlFrame(None, "Simple HTML")
    frm.Bind(wx.html.EVT_HTML_LINK_CLICKED,OnClickWord)
    frm.Show()
    
    app.MainLoop()