【问题标题】:configure tkinter text widget as code editor. select words on doubleclick将 tkinter 文本小部件配置为代码编辑器。双击选择单词
【发布时间】:2017-05-11 20:38:11
【问题描述】:

我尝试在 python 中使用 tkinter 构建代码编辑器。我正在使用文本小部件。现在我坚持双击代码选择。当我有这一行时:if (variable<0) return 0; 并且我双击variable 他会像这样(variable<0) 标记从一个空间到另一个空间的所有字符。

所以我在 tkinter 库中搜索了 doublick 函数并找到了这个:

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

现在我卡住了。有人可以帮我编辑吗?也许它与word有关?

【问题讨论】:

  • 你在windows上运行吗?
  • 是的,Windows 10。Python 3.5。 Tkinter 8.6

标签: python text tkinter widget


【解决方案1】:

Tkinter 是一个 tcl 解释器的包装器,它加载 tk 库。 Tcl 使用一些全局变量来定义它认为是“词”的东西,并在其实现的各个地方使用这些变量。最明显的是,这些用于处理文本和条目小部件的鼠标和键绑定。

在 Windows 上,“单词”被定义为除空格以外的任何内容,默认情况下双击会选择“单词”。因此,双击variable&lt;0 会选择空格之间的所有内容。在其他平台上,“单词”仅定义为大小写字母、数字和下划线。

要让 tkinter 将单词视为仅由字母、数字和下划线组成,您可以将这些全局变量重新定义为匹配这些字符(或您想要的任何其他字符)的正则表达式。

在以下示例中,它应强制将所有平台的单词定义为字母、数字和下划线:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多