2017-07-14 41 views
-1

我已經添加驗證到我的tkinter入口小部件,只允許numbers.I添加了代碼,我認爲還允許一個條目小部件爲空以啓用我的刷新和重新啓動功能。驗證,防止刷新/重新啓動 - tkinter

當按下重新啓動或參照按鈕時,我希望清除條目窗口小部件和文本區域。目前只有文本區域正在清除。數字保留在條目窗口小部件中。建議修改我的代碼將不勝感激。

def __init__(self, parent, controller): 
    tk.Frame.__init__(self, parent) 
    self.controller = controller 
    ... 
    vcmd = (self.register(self.onValidate), '%S') 
    self.weight_entry = tk.Entry(self, validate='key', vcmd = vcmd) 
    self.weight_entry.pack(pady = 10) 
    self.text = tk.Text(self) 
    self.text.pack(pady = 10) 
    self.text.config(state='disabled') 
    Restart_button = tk.Button(self, text="Restart", command=self.restart) 
    Refresh_button = tk.Button(self, text="Refresh", command=self.refresh) 
    ... 


# Code below adds validation to the Entry widget so only numbers can be entered 
def onValidate(self,s): 
    if (self.weight_entry ==""):"""Not sure if this is correct. Taken from another answer on SO.""" 
     return True 
    if s in ['0','1','2', '3', '4', '5', '6', '7', '8', '9']: 
     return True 
    else: 
     self.bell() # adds a sound effect to error 
     self.text.delete(1.0, tk.END) # deletes the error message if valid entry provided 
     return False 

def restart(self): 
    self.refresh() 
    self.controller.show_frame("StartPage") 

def refresh(self): 
    self.weight_entry.delete(0,tk.END) 
    self.text.config(state='normal') 
    self.text.delete("1.0", "end") 
    self.text.config(state='disabled') 

回答

1

爲什麼你不能刪除的條目的全部內容,是因爲在onValidate你期望s是一個單一的數字,但如果您的條目中包含「123」,當你調用delete(0, "end"),然後s =' 123',所以onValidate返回False。

爲了解決這個問題,你可以這樣做:

def onValidate(self, s): 
    if s.isdigit(): # no need to test if the entry is empty because the deleted text contains only digits 
     return True 
    else: 
     self.bell() # adds a sound effect to error 
     self.text.delete(1.0, tk.END) # deletes the error message if valid entry provided 
     return False