简体   繁体   English

Tkinter 中的条目小部件<key>绑定</key>

[英]Entry Widget in Tkinter with <Key> Bind

Can anyone help me determine why the print statements seem to lag behind the input for this code?谁能帮我确定为什么打印语句似乎落后于该代码的输入? If you run this short program and type 1,2,3,4,5 into the input entry widget, the event triggering the method gets the current value of the typed_string Stringvar, but it lags 1 behind the input.如果您运行这个简短的程序并在输入条目小部件中键入 1,2,3,4,5,则触发该方法的事件将获取 typed_string Stringvar 的当前值,但它比输入滞后 1。 Can someone explain why?有人可以解释为什么吗? Better yet, does anyone know of a way that any keypress to an entry widget that produces text will call the displayed value of the input variable?更好的是,有没有人知道任何对生成文本的条目小部件的按键都会调用输入变量的显示值的方式? Current version of python is 3.8 python 的当前版本是 3.8


import tkinter
from tkinter import *

class UI():
    def __init__(self, master):
        self.typed_string = StringVar()
        self.typed_string.set("")

        self.new_entry = tkinter.Entry(master, textvariable=self.typed_string)
        self.new_entry.pack()
        self.new_entry.bind("<Key>",self.check_string)

    def check_string(self, event):
        retrieved_string = self.typed_string.get()
        print(retrieved_string, " was retrieved string")
        print(self.new_entry.get(), " was get for entry widget")

def main():
    root = Tk()
    new_ui = UI(root)
    root.mainloop()

if __name__ == '__main__':
    main()

input field with terminal output shown显示端子 output 的输入字段

If you replace:如果您更换:

    self.new_entry.bind("<Key>",self.check_string)

with

    self.new_entry.bind("<KeyRelease>",self.check_string)

it does what I think you want it to do.它做我认为你想要它做的事情。

Reason: The Key event is triggered before the character of that key is added to the StringVar variable;原因:在该键的字符添加到StringVar变量之前触发了Key事件; or perhaps more accurately, before the key press is processed, one result of which is to add the character of the key to the variable if it is a normal printable key.或者更准确地说,在按键被处理之前,如果它是一个普通的可打印按键,其结果之一就是将按键的字符添加到变量中。 The KeyRelease event is triggered after the keypress is processed and therefore after the character has already been added to the variable when you try to print it. KeyRelease事件在按键处理完成触发,因此在您尝试打印字符时已将字符添加到变量中。

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

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