簡體   English   中英

綁定事件在鍵入的字符被放入條目之前運行

[英]Bind event runs before character typed is put in entry

我正在用 tkinter 制作一個特殊的文本小部件,它應該有工作縮進。 為了讓縮進起作用,我將 function 綁定到 Enter 按鈕上。 此綁定在實際鍵入的字符之后進行綁定之前工作正常,但它不會與此 function 一起工作。有人可以幫我嗎?

工作綁定:

def double_parentheses(self, event):
        main_text_box_anchor = str(self.text.index("insert")).split(".")
        self.text.insert(INSERT, ")")
        self.text.mark_set(INSERT, str(main_text_box_anchor[0]) + "." + 
        str(int(main_text_box_anchor[1])))
#later in the code
scroll.text.bind("(", scroll.double_parentheses)

這使括號按順序插入在它們中間

不工作:

def new_line_indent(self, event):
        line = self.text.get("insert linestart", "insert lineend")
        editable_line = str(line)
        if editable_line != "":
            if editable_line[-1] == ":":
                if "\t" in editable_line:
                    for i in range(editable_line.count("\t")):
                        self.text.insert("insert", "\t")
                else:    
                    self.text.insert("insert", "\t")
            elif "\t" in editable_line:
                for i in range(editable_line.count("\t")):
                    self.text.insert("insert", "\t")
#Later in the code
scroll.text.bind("<Return>", scroll.new_line_indent)

這會將選項卡放入,但它會在創建新行之前完成,我不知道為什么。 我究竟做錯了什么?

這會將選項卡放入,但它會在創建新行之前完成,我不知道為什么。

簡短的回答是您的綁定發生在內置鍵綁定之前。 因此,在 tkinter 實際插入換行符之前調用您的 function。

你應該讓你的代碼插入換行符,執行你的其他操作,然后返回“break”以防止默認行為發生。

有關如何處理綁定的更詳盡的解釋,請參閱此答案

這是一個工作示例:

def new_line_indent(self, event):
    # get the text of the current line
    line = self.text.get("insert linestart", "insert lineend")

    # insert the newline
    self.text.insert("insert", "\n")

    # insert indentation if line ends with ":"
    if line and line[-1] == ":":

        # get current indentation, then insert it
        leading_whitespace = self.get_leading_whitespace(line)
        self.text.insert("insert", leading_whitespace)

        # add an additional level of indentation
        self.text.insert("insert", "\t")

    # since we already inserted the newline, make sure that
    # the default bindings do not
    return "break"

def get_leading_whitespace(self, line):
    n = len(line) - len(line.lstrip())
    return line[:n]

除了 Bryan 建議的解決方案,您可以綁定<KeyRelease-Return>而不是<Return> 然后回調將在添加換行符后執行:

    def new_line_indent(self, event):
        # get previous line
        line = self.text.get("insert-1c linestart", "insert-1c lineend")
        editable_line = str(line)
        if editable_line != "":
            for i in range(editable_line.count("\t")):
                self.text.insert("insert", "\t")
            if editable_line[-1] == ":":
                self.text.insert("insert", "\t")

...
#Later in the code
scroll.text.bind("<KeyRelease-Return>", scroll.new_line_indent)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM