Skip to main content
 首页 » 编程设计

python之wordend 不考虑撇号

2024年10月25日12mayingbao

如果我们想分析鼠标光标下的单词,我们可以使用:

text.get('current wordstart', 'current wordend')  

但是,这不考虑带有撇号的单词。
还有其他方法吗?

请您参考如下方法:

Christian Gollwitzer 在 comp.lang.tcl为我提供了解决方法。
这是我的 Python 3.4 测试代码:

import tkinter 
import tkinter.messagebox as messagebox 
 
class Creator(object): 
 
    def __init__(self): 
 
        root = self.root = tkinter.Tk() 
 
        # Main Frame 
        f_main = tkinter.Frame(root, borderwidth=6, relief='flat') 
        f_main.grid(row=0, column=0, sticky='nsew') 
 
        # Text widget and frame 
        f_txt = tkinter.Frame(f_main, borderwidth=2, relief="sunken") 
        f_txt.config(width=768, height=768) 
        f_txt.pack(padx=4, pady=4, side="bottom", fill="both", expand=True) 
 
        my_txt = self.text = tkinter.Text(f_txt) 
        my_txt.config(undo=True, wrap='word') 
        my_txt.grid(row=0, column=0, sticky="nsew") 
        my_txt.bind("<ButtonRelease-3>", self.test) 
        my_txt.focus_set() 
 
    def test(self, event=None): 
        txt = str(self.text) 
        a = "::tk::TextPrevPos {} current tcl_wordBreakBefore".format(txt) 
        b = "::tk::TextNextPos {} current tcl_wordBreakAfter".format(txt) 
        ind1 = self.root.tk.eval(a) 
        ind2 = self.root.tk.eval(b) 
        x = self.text.get(ind1, ind2) 
        messagebox.showinfo('info', x) 
 
GUI = Creator() 
GUI.root.mainloop()