python - 清除条目小部件框

标签 python tkinter widget tkinter-entry

我想使用输入小部件来获取 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)会在 字符出现在小部件中之前触发。

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

关于python - 清除条目小部件框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12638664/

相关文章:

python - 使用 base64 编码,为什么我得到错误的答案?

python - Conda 环境和 Jupyter Notebook,Python 3.9.2

python - 在 Slurm 集群上运行 TensorFlow?

Python百分比计算器

python - 更改 tk.optionmenu 小部件的颜色

javascript - 单击按钮后显示 Google 翻译小部件

python - 将闭合曲线拟合到一组离散点并找到其周长

python - Tkinter.Text 索引表达式和 unicode

jquery UI datepicker,是否可以使某些日期不可选择?

Android 小部件未调用服务 onStart