简体   繁体   中英

The text widget insert method of tkinter not working

I have been working on one application where in I want to autocomplete things like brackets round curly square. I had done that using the insert method of tkinter with the tk.INSERT constant as index like so:

def autocomplete(self, val) :
    if val == '(' :
        self.insert(tk.INSERT, ')')
    elif val == '{' :
        self.insert(tk.INSERT, '}')
    elif val == '[' :
        self.insert(tk.INSERT, ']')
    elif val == '\'' :
        self.insert(tk.INSERT, '\'')
        self.mark_set('sentinel', str(float(self.index(tk.INSERT)) - 0.1))
    elif val == '\"' :
        self.insert(tk.INSERT, '\"')
        self.mark_set('sentinel', str(float(self.index(tk.INSERT)) - 0.1))
    elif val == ':' :
        text = self.get(1.0, tk.INSERT).strip().replace(' ', '')
        
        if text[(text.index(':') - 1) : text.index(':')] == ')' :
            self.insert(tk.INSERT, '\n\t')
    return

This is a function which is within a text widget where the init has the following bindings attached:

self.bind('(', lambda x : self.autocomplete('('))
self.bind('{', lambda x : self.autocomplete('{'))
self.bind('[', lambda x : self.autocomplete('['))
self.bind(':', lambda x : self.autocomplete(':'))
self.bind('\'', lambda x : self.autocomplete('\''))
self.bind('\"', lambda x : self.autocomplete('\"'))

And when I type any of these like lets take the eg of brackets, then it shows the output somewhat not right.

)(

Here is also a snapshot of the same:
文本小部件对问题的实际快照

You see I want the other bracket to appear at the end but it does not.

This is because the binding is triggered before the character is inserted in the text widget. To fix this you can bind to '<KeyRelease-..>' instead, where .. needs to be replaced by the keysym.

self.bind('<KeyRelease-parenleft>', lambda x : self.autocomplete('('))
self.bind('<KeyRelease-braceleft>', lambda x : self.autocomplete('{'))
self.bind('<KeyRelease-bracketleft>', lambda x : self.autocomplete('['))
self.bind('<KeyRelease-colon>', lambda x : self.autocomplete(':'))
self.bind('<KeyRelease-apostrophe>', lambda x : self.autocomplete('\''))
self.bind('<KeyRelease-quotedbl>', lambda x : self.autocomplete('\"'))

The keysym of special characters are not always the same for all OS, so here is a trick to find the keysym of any key on your system:

import tkinter as tk
root = tk.Tk()
root.bind('<Key>', lambda ev: print(ev.keysym))
root.mainloop()

Just press the key to get the keysym

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