简体   繁体   English

将tkinter文本小部件配置为代码编辑器。 在doubleclick上选择单词

[英]configure tkinter text widget as code editor. select words on doubleclick

i try to build an code editor with tkinter in python. 我尝试在python中使用tkinter构建代码编辑器。 i am using the text widget. 我正在使用文本小部件。 now i stuck with the code selection on double click. 现在我坚持双击代码选择。 when i have this line: if (variable<0) return 0; 当我有这行: if (variable<0) return 0; and i double click on variable he marks all chars from space to space like this (variable<0) . 我双击variable他将所有字符从一个空格标记到另一个空格(variable<0)

so i searched the tkinter lib for the doublick function and found this: 所以我在tkinter库中搜索了doublick函数,发现了这一点:

bind Text <Double-1> {
    set tk::Priv(selectMode) word
    tk::TextSelectTo %W %x %y
    catch {%W mark set insert sel.first}
}

and now i stuck. 现在我卡住了。 can someone help me to edit it? 有人可以帮我编辑吗? maybe it has something todo with word ? 也许与word

Tkinter is a wrapper around a tcl interpreter which loads the tk library. Tkinter是tcl解释器的包装,该解释器加载tk库。 Tcl uses some global variables to define what it considers to be a "word", and uses these variables in various places in its implementation. Tcl使用一些全局变量来定义它认为是“单词”的单词,并在其实现的各个位置使用这些变量。 Most visibly, these are used to handle mouse and key bindings for the text and entry widgets. 最明显的是,它们用于处理文本和输入小部件的鼠标和键绑定。

On windows, a "word" is defined as anything other than a space, and double-click by default selects a "word". 在Windows上,“单词”定义为除空格以外的任何内容,默认情况下,双击将选择一个“单词”。 Thus, double-clicking on variable<0 selections everything between whitespace. 因此,双击variable<0选择空白之间的所有内容。 On other platforms a "word" is defined as upper and lowercase letters, numbers, and the underscore only. 在其他平台上,“单词”仅定义为大写和小写字母,数字和下划线。

To get tkinter to treat words as only made up by letters, numbers, and underscores, you can redefine these global variables to be a regular expression that matches those characters (or any other characters that you want). 要使tkinter将单词视为仅由字母,数字和下划线组成的单词,可以将这些全局变量重新定义为与这些字符(或所需的任何其他字符)匹配的正则表达式。

In the following example, it should force words to be defined only as letters, numbers, and underscores for all platforms: 在以下示例中,对于所有平台,应强制将单词定义为仅字母,数字和下划线:

import tkinter as tk

def set_word_boundaries(root):
    # this first statement triggers tcl to autoload the library
    # that defines the variables we want to override.  
    root.tk.call('tcl_wordBreakAfter', '', 0) 

    # this defines what tcl considers to be a "word". For more
    # information see http://www.tcl.tk/man/tcl8.5/TclCmd/library.htm#M19
    root.tk.call('set', 'tcl_wordchars', '[a-zA-Z0-9_]')
    root.tk.call('set', 'tcl_nonwordchars', '[^a-zA-Z0-9_]')

root = tk.Tk()
set_word_boundaries(root)

text = tk.Text(root)
text.pack(fill="both", expand=True)
text.insert("end", "if (variable<0):  return 0;\n")

root.mainloop()

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

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