如何绑定鼠标事件,例如在 TextCtrl 的一个单词上左下.请参阅以 # 开头的代码



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

导入 WX

类文本框架(wx.框架):

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" 

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

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

相信有办法确定您在TextCtrl中单击或悬停在哪个单词上。
但是,您可以通过预定义单词占用的区域并使用鼠标位置的坐标来执行所需的操作。
例如:您知道单词"保留"占据了 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查找字符在指定点的行和列。

编辑:这是修改后的代码:
注意:即使您指定了左键单击,我也已将事件保留为右键单击

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

相关内容

  • 没有找到相关文章

最新更新