如何在 TextCtrl 的一个单词上绑定像 leftdown 这样的鼠标事件。看到代码以#开头?

How can I bind mouse event like leftdown on one word of TextCtrl. see the code start with #?

当我将文本附加到 . 下面是我写的代码。 我的英语不是很好。感谢您的帮助。

导入 wx

class 文本框(wx.Frame):

def __init__(self):   
    wx.Frame.__init__(self, None, -1, 'Text Entry Example',   
            size=(300, 250))   
    panel = wx.Panel(self, -1)   
    richLabel = wx.StaticText(panel, -1, "Rich Text")   
    richText = wx.TextCtrl(panel, -1,   
            "If supported by the native control, this is reversed, and this is a different font.",   
            size=(200, 100), style=wx.TE_MULTILINE|wx.TE_RICH2)   
    richText.Bind(wx.EVT_RIGHT_DOWN, self.OnTextCtrl1LeftDown) 
    richText.SetInsertionPoint(0) 

    #? how can I bind mouse event like leftdown on Text below 
    #? how can I bind mouse event like leftdown on Text below 
    richText.SetStyle(44, 52, wx.TextAttr("white", "black"))   

    points = richText.GetFont().GetPointSize()   
    print points,type(points) 
    f = wx.Font(points + 10, wx.ROMAN, wx.ITALIC, wx.BOLD, True)   
    richText.SetStyle(68, 82, wx.TextAttr("blue", wx.NullColour, f))   

    sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)   
    sizer.AddMany([richLabel, richText])   
    panel.SetSizer(sizer) 
def OnTextCtrl1LeftDown(self,event): 
    print "clientwx,leftdown" 

我认为没有办法确定您在 TextCtrl 中单击或悬停在哪个词上。
但是,您可以通过预定义单词占用的区域并使用鼠标位置的坐标来执行您想要的操作。
例如:您知道单词 "reserved" 占据了 44 和 52 之间的区域,因为您为其分配了样式,请在 OnTextCtrl1LeftDown 函数中测试它。
获取鼠标位置并执行 HitTest 使用:

m_pos = event.GetPosition()  # position tuple
self.richText.HitTest(m_pos)
#now code here to test if the column and row positions are within your parameters#

HitTest 查找字符在指定点的行和列。

编辑: 这是您修改后的代码:
注意:即使您指定了 LEFT click

,我也将事件保留为 RIGHT click
import wx

class TextFrame(wx.Frame):

    def __init__(self):   
        wx.Frame.__init__(self, None, -1, 'Text Entry Example',   
                size=(300, 250))   
        self.panel = wx.Panel(self, -1)   
        self.richLabel = wx.StaticText(self.panel, -1, "Rich Text")   
        self.richText = wx.TextCtrl(self.panel, -1,   
                "If supported by the native control, this is reversed, and this is a different font.",   
                size=(200, 100), style=wx.TE_MULTILINE|wx.TE_RICH2)   
        self.richText.Bind(wx.EVT_RIGHT_DOWN, self.OnTextCtrl1LeftDown) 
        self.richText.SetInsertionPoint(0) 

        #? how can I bind mouse event like leftdown on Text below 
        #? how can I bind mouse event like leftdown on Text below 
        self.richText.SetStyle(44, 52, wx.TextAttr("white", "black"))   

        points = self.richText.GetFont().GetPointSize()   
        f = wx.Font(points + 10, wx.ROMAN, wx.ITALIC, wx.BOLD, True)   
        self.richText.SetStyle(68, 82, wx.TextAttr("blue", wx.NullColour, f))   

        sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)   
        sizer.AddMany([self.richLabel, self.richText])   
        self.panel.SetSizer(sizer) 


    def OnTextCtrl1LeftDown(self,event): 
        m_pos = event.GetPosition()  # position tuple
        word_pos = self.richText.HitTest(m_pos)
        if word_pos[0] == 0:
            if word_pos[1] > 43 and word_pos[1] < 53:
                print "You clicked on the word 'reserved'" 
            if word_pos[1] > 67 and word_pos[1] < 83:
            print "You clicked on the words 'Different Font'" 

if __name__ == '__main__':
    test = wx.App()
    TextFrame().Show()
    test.MainLoop()    

受这个问答的启发,我写了一个更通用的单词点击程序。它会在您单击的文本框中找到单词:

import wx

sample_text = """Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
eprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum."""

class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, 'Word Clicker')
        pnl = wx.Panel(self, wx.ID_ANY)
        lbl = wx.StaticText(pnl, wx.ID_ANY, "Source Text")
        self.richText = txt = wx.TextCtrl(
            pnl,
            wx.ID_ANY,
            sample_text,
            style=wx.TE_MULTILINE | wx.TE_RICH2 | wx.TE_READONLY,
        )
        self.found = fnd = wx.StaticText(pnl, wx.ID_ANY, "<result goes here>")
        txt.Bind(wx.EVT_LEFT_DOWN, self.OnGetWord)
        txt.SetInsertionPoint(0)
        txt.SetCursor(wx.Cursor(wx.CURSOR_HAND))
        szr = wx.BoxSizer(wx.VERTICAL)
        szr.AddMany([(lbl,0),(txt,1,wx.EXPAND), (fnd,0,wx.EXPAND)])
        pnl.SetSizerAndFit(szr)


    def OnGetWord(self, event):
        xy_pos = event.GetPosition()
        _, word_pos = self.richText.HitTestPos(xy_pos)
        search_text = self.richText.GetValue()
        left_pos = right_pos = word_pos
        if word_pos < len(search_text) and search_text[word_pos].isalnum():
            try:
                while left_pos >= 0 and search_text[left_pos].isalnum():
                    left_pos -= 1
                while right_pos <= len(search_text) and search_text[right_pos].isalnum():
                    right_pos += 1
                found_word = search_text[left_pos + 1 : right_pos]
                print(f"Found: '{found_word}'")
            except Exception as e:
                found_word = "<" + str(e) + ">"
        else:
            found_word = "<Not On Word>"
        self.found.SetLabel(found_word)

if __name__ == '__main__':
    app = wx.App()
    MyFrame().Show()
    app.MainLoop()