简体   繁体   English

更改Python Tkinter中单词的定义?

[英]Change the definition of a word in Python Tkinter?

When double clicking a word in a Text -widget the clicked word is selected. 双击“ Text部件中的单词时,将选择单击的单词。 Tkinter's understanding of what a word is, however, is impractical for my use case. 然而,对于我的用例而言,Tkinter对单词是什么的理解是不切实际的。

Effbot explains what Tkinter considers to be a word but not how to change that. Effbot解释了Tkinter认为是什么的单词,但没有说明如何更改。 Is it possible to change Tkinter's definition of a word so that it recognizes hyphens as part of a word? 是否可以更改Tkinter对单词的定义,以便将连字符识别为单词的一部分? Ie I would like to select a text like --help or --version or -U with a double click. 即我想双击选择--help--version-U类的文本。

In the answer that curtisk has provided a link to Bryan Oakley states that this is not possible: 答案中 ,curtisk提供了指向Bryan Oakley的链接,指出这是不可能的:

You can't modify how "wordstart" defines "words". 您无法修改“ wordstart”如何定义“ words”。

But based on his answer I have developed the following method select_current_word , the code around is just to illustrate it's usage. 但是根据他的回答,我开发了以下方法select_current_word ,周围的代码仅是为了说明其用法。

import Tkinter as tk

class MyText(tk.Text):

     def __init__(self, **kw):
         tk.Text.__init__(self, **kw)
         self.bind('<Double-Button-1>', self.select_current_word)

     def select_current_word(self, event):
         i0 = self.search(r'[-\w]+', tk.CURRENT+'+1c', backwards=True, regexp=True)
         i1 = self.search(r'[^-\w]+', i0, forwards=True, regexp=True)
         self.tag_remove(tk.SEL, '1.0', tk.END)
         self.tag_add(tk.SEL, i0, i1)
         self.update()
         return 'break'

if __name__=='__main__':
     t = MyText()
     t.pack(expand=True, fill=tk.BOTH)
     t.insert('1.0', """
Options:
  General Options:
     -h, --help                       Print this help text and exit
     --version                        Print program version and exit
     -U, --update                     Update this program to latest version.
""".strip())
     t.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM