简体   繁体   中英

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

i try to build an code editor with tkinter in python. 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; and i double click on variable he marks all chars from space to space like this (variable<0) .

so i searched the tkinter lib for the doublick function and found this:

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 ?

Tkinter is a wrapper around a tcl interpreter which loads the tk library. Tcl uses some global variables to define what it considers to be a "word", and uses these variables in various places in its implementation. 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". Thus, double-clicking on variable<0 selections everything between whitespace. 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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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