Python Tkinter:删除字符串的最后一个字符
我正在创建一个只允许输入数字的条目。如果该字符不是整数,我目前正在删除刚刚输入的字符。如果有人会将“空白”替换为需要进入的地方,那将会有很多帮助。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()
你也可以改变上面也行,这样:
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)
干得好把一个工作示例供我们使用,帮助速度这一点。
我明白为什么-1会工作,但由于某种原因它会删除整个字符串。任何想法为什么? – Crispy 2012-07-07 02:40:34
似乎tkinter需要'-1'作为任何事物的'默认',所以你可能必须对它很棘手。您可以不用像现在这样删除它,而是可以取出当前设置的字符串,取出最后一个字符,然后将其放回到小部件中。看看更新回答 – TankorSmash 2012-07-07 02:50:55
Hackish,但这个工程:'e.delete(len(e.get()) - 1,'end')'。 – 2012-07-07 02:54:48
如果有人按ctrl-V并粘贴更长的字符串会怎么样? – 2012-07-07 02:37:50
我想我应该找到一种方法,然后搜索字符串并删除任何不是数字 – Crispy 2012-07-07 02:44:06
请参阅[验证条目窗口小部件](http://effbot.org/zone/tkinter-entry-validate.htm),特别是IntegerEntry子类。 – 2012-07-07 02:44:20