2012-09-28 57 views
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) 

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

回答

1

你正在進行輸入驗證的方式是錯誤的。你提出的問題不能用你發佈的代碼來完成。首先,正如你發現的那樣,當你在<<Key>>上綁定時,默認情況下綁定在之前觸發,該角色出現在widget中。

我可以給你解決方法,但正確的答案是使用內置的設施進行輸入驗證。請參閱條目窗口小部件的validatecommandvalidate屬性。 This answer問題Interactively validating Entry widget content in tkinter會告訴你如何。該答案顯示瞭如何驗證上/下,但很容易將其與一組有效字符進行比較。

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。

(我敢肯定有一個更好的方式來寫驗證,但據我可以看到沒有工作)

+0

在這種特殊情況下,我建議你刪除所有那些額外的參數,因爲你不使用它們。爲了說明的目的,我把它們放在其他答案中,但是在這裏你並沒有使用它們,所以它們只能使解決方案比需要的更復雜。 –

+0

hanks Bryan和Jdog,我會嘗試這個驗證碼。如果可能,我想保留OnKeyPress事件處理程序 - 如果輸入有效,我實際上使用它來移動到另一個輸入小部件;所以一個後續問題 - 你可以使用驗證和事件處理程序來完成任務嗎?如果你可以首先驗證或事件處理程序? – paddypantsonfire

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() 

你可以在任何你想使用的環境下使用它,這只是一個例子