简体   繁体   English

tkinter 的文本小部件插入方法不起作用

[英]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:我已经使用tk.INSERT的 insert 方法将tk.INSERT常量作为索引完成了,如下所示:

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:这是一个位于文本小部件中的函数,其中 init 附加了以下绑定:

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.要解决此问题,您可以改为绑定到 '<KeyRelease-..>',其中..需要由键符替换。

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只需按下键即可获得键符

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

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