0

当我将 Text 附加到 . 下面是我写的代码。我英语不是很好。谢谢你的帮助。

导入 wx

类TextFrame(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" 
4

2 回答 2

1

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

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()
于 2021-05-02T20:44:10.587 回答
0

我不相信有一种方法可以确定您单击或悬停在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在指定点查找字符的行和列。

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

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()    
于 2016-03-17T09:39:23.340 回答