Skip to main content
 首页 » 编程设计

python之清除条目小部件框

2025年05月04日14dudu

我想使用输入小部件来获取 1 到 9 之间的数字。如果按下任何其他键,我想将其从显示中删除。

    def onKeyPress(event): 
        if event.char in ['1', '2', '3', '4', '5', '6', '7', '8', '9'] 
            ...do something 
            return 
 
        # HERE I TRY AND REMOVE AN INVALID CHARACTER FROM THE SCREEN 
        # at this point the character is: 
        #   1) visible on the screen 
        #   2) held in the event 
        #   3) NOT YET in the entry widgets string 
        # as the following code shows... 
        print ">>>>", event.char, ">>>>", self._entry.get() 
        # it appeARS that the entry widget string buffer is always 1 character behind the event handler 
 
        # so the following code WILL NOT remove it from the screen... 
        self._entry.delete(0, END) 
        self._entry.insert(0, "   ") 
 
    # here i bind the event handler     
    self._entry.bind('<Key>',  onKeyPress) 

好的,那么我该如何清除屏幕呢?

请您参考如下方法:

您进行输入验证的方式是错误的。您发布的代码无法完成您的要求。其一,正如您所发现的,当您绑定(bind) <<Key>> 时,默认情况下绑定(bind)会在 字符出现在小部件中之前触发。

我可以为您提供解决方法,但正确的答案是使用内置工具进行输入验证。查看 validatecommand和 validate条目小部件的属性。 This answer问题Interactively validating Entry widget content in tkinter会告诉你怎么做。该答案显示了如何针对上限/下限进行验证,但很容易更改它以与一组有效字符进行比较。