Skip to main content
 首页 » 编程设计

python之使用 wxPython 在 Python 中的文本上鼠标事件

2025年05月04日9TianFang

这就是我想要做的:

我创建了一个窗口,上面显示了文本,作为用户,我点击了文本, 示例:显示的文字是。

'Hello World, I am a Python program.' 

因此,如果用户单击单词,我希望它生成一个事件,它会进入一个函数,我想在函数中做一些事情(比如改变那个单词的颜色,所以我还需要跟踪我点击了哪个词)

我不太确定该怎么做,我可以将每个单词都设为一个按钮,但那样会很丑陋。

请您参考如下方法:

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() 

或使用 htmlwin ...但它强调了所有单词...我无法弄清楚如何不这样做

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()