2012-07-07 316 views
4

我正在創建一個只允許輸入數字的條目。如果該字符不是整數,我目前正在刪除剛剛輸入的字符。如果有人會將「空白」替換爲需要進入的地方,那將會有很多幫助。Python Tkinter:刪除字符串的最後一個字符

import Tkinter as tk 

class Test(tk.Tk): 

    def __init__(self): 

     tk.Tk.__init__(self) 

     self.e = tk.Entry(self) 
     self.e.pack() 
     self.e.bind("<KeyRelease>", self.on_KeyRelease) 

     tk.mainloop() 



    def on_KeyRelease(self, event): 

     #Check to see if string consists of only integers 
     if self.e.get().isdigit() == False: 

      self.e.delete("BLANK", 'end')#I need to replace 0 with the last character of the string 

     else: 
      #print the string of integers 
      print self.e.get() 




test = Test() 
+0

如果有人按ctrl-V並粘貼更長的字符串會怎麼樣? – 2012-07-07 02:37:50

+0

我想我應該找到一種方法,然後搜索字符串並刪除任何不是數字 – Crispy 2012-07-07 02:44:06

+1

請參閱[驗證條目窗口小部件](http://effbot.org/zone/tkinter-entry-validate.htm),特別是IntegerEntry子類。 – 2012-07-07 02:44:20

回答

5

你也可以改變上面也行,這樣:

if not self.e.get().isdigit(): 
     #take the string currently in the widget, all the way up to the last character 
     txt = self.e.get()[:-1] 
     #clear the widget of text 
     self.e.delete(0, tk.END) 
     #insert the new string, sans the last character 
     self.e.insert(0, txt) 

或:

if not self.e.get().isdigit(): 
    #get the length of the string in the widget, and subtract one, and delete everything up to the end 
    self.e.delete(len(self.e.get)-1, tk.END) 

幹得好把一個工作示例供我們使用,幫助速度這一點。

+0

我明白爲什麼-1會工作,但由於某種原因它會刪除整個字符串。任何想法爲什麼? – Crispy 2012-07-07 02:40:34

+0

似乎tkinter需要'-1'作爲任何事物的'默認',所以你可能必須對它很棘手。您可以不用像現在這樣刪除它,而是可以取出當前設置的字符串,取出最後一個字符,然後將其放回到小部件中。看看更新回答 – TankorSmash 2012-07-07 02:50:55

+1

Hackish,但這個工程:'e.delete(len(e.get()) - 1,'end')'。 – 2012-07-07 02:54:48

1

如果您正在進行數據驗證,您應該使用條目小部件的內置功能,特別是validatecommandvalidate屬性。

有關如何識別這些屬性的說明,請參閱this answer

相關問題