2017-03-17 16 views
0

如果輸入字母作爲輸入,給出錯誤並告訴用戶只輸入數字的最佳方式是什麼?代碼不工作:如何告訴用戶只有在Python/Tkinter中輸入字符串時才使用整數?

if self.localid_entry.get() == int(self.localid_entry.get(): 
       self.answer_label['text'] = "Use numbers only for I.D." 

在Tkinter的與得到的變量:

self.localid2_entry = ttk.Entry(self, width=5) 
    self.localid2_entry.grid(column=3, row=2) 
+0

使用'嘗試/ except'捕獲錯誤時int()失敗。 – Barmar

回答

0

事情是這樣的:

try: 
    i = int(self.localid_entry.get()) 

except ValueError: 
    #Handle the exception 
    print 'Please enter an integer' 
3

最好的解決辦法是使用驗證功能只允許整數,這樣用戶完成後就不必擔心驗證了。

有關僅允許字母的示例,請參閱https://stackoverflow.com/a/4140988/7432。把它轉換成只允許整數是很簡單的。

0

布賴恩有正確的答案,但使用tkinter的驗證系統是相當龐大的。我更願意在變量上使用跟蹤來檢查。舉例來說,我可以做一個新類型的條目只接受數字:

class Prox(ttk.Entry): 
    '''A Entry widget that only accepts digits''' 
    def __init__(self, master=None, **kwargs): 
     self.var = tk.StringVar(master) 
     self.var.trace('w', self.validate) 
     ttk.Entry.__init__(self, master, textvariable=self.var, **kwargs) 
     self.get, self.set = self.var.get, self.var.set 
    def validate(self, *args): 
     value = self.get() 
     if not value.isdigit(): 
      self.set(''.join(x for x in value if x.isdigit())) 

你會用它就像一個文本輸入構件:

self.localid2_entry = Prox(self, width=5) 
self.localid2_entry.grid(column=3, row=2) 
相關問題