清除条目小部件框

时间:2012-09-28 10:55:49

标签: 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)

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

3 个答案:

答案 0 :(得分:1)

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

我可以给你解决方法,但正确的答案是使用内置工具进行输入验证。请参阅条目小部件的validatecommandvalidate属性。问题This answerInteractively validating Entry widget content in tkinter将告诉您如何操作。该答案显示了如何验证上/下,但很容易将其更改为与一组有效字符进行比较。

答案 1 :(得分:0)

import Tkinter as tk

class MyApp():
    def __init__(self):
        self.root = tk.Tk()
        vcmd = (self.root.register(self.OnValidate), 
                '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
        self.entry = tk.Entry(self.root, validate="key", 
                              validatecommand=vcmd)
        self.entry.pack()
        self.root.mainloop()

    def OnValidate(self, d, i, P, s, S, v, V, W):
        # only allow integers 1-9
        if P == "":
            return True
        try:
            newvalue = int(P)
        except ValueError:
            return False
        else:
            if newvalue > 0 and newvalue < 10:
                return True
            else:
                return False

app=MyApp()

this回答,修改后的验证只允许整数1-9。

(我确信有更好的方法来编写验证,但就我所见,它可以完成这项工作。)

答案 2 :(得分:0)

清除条目小部件的一种简单方法是:

from tkinter import *

tk = Tk()


# create entry widget

evalue = StringVar()
e = Entry(tk,width=20,textvariable=evalue)
e.pack()


def clear(evt):
    evalue.set("")   # the line that removes text from Entry widget

tk.bind_all('<KeyPress-Return>',clear)  #clears when Enter is pressed
tk.mainloop()

你可以在任何你想要的上下文中使用它,这只是一个例子