2

我想使用一个条目小部件来获取 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)

好的,我怎样才能清除屏幕?

4

3 回答 3

1

您进行输入验证的方式是错误的。你所问的不能用你发布的代码来完成。一方面,正如您所发现的,当您绑定 on 时,默认情况下绑定会在角色出现在小部件中之前<<Key>>触发。

我可以为您提供解决方法,但正确的答案是使用内置工具进行输入验证。查看条目小部件的validatecommandvalidate属性。This answer to the question Interactively validate Entry widget content in tkinter将向您展示如何。该答案显示了如何针对上/下进行验证,但是很容易将其更改为与一组有效字符进行比较。

于 2012-09-28T11:11:48.193 回答
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()

取自这个答案,修改后的验证只允许整数 1-9。

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

于 2012-09-28T11:46:44.067 回答
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()

您可以在任何您希望的上下文中使用它,这只是一个示例

于 2013-07-09T16:26:35.570 回答