Python Tkinter:删除字符串的最后一个字符
我正在做一个只允许输入数字的条目。如果输入的字符不是一个整数,我目前无法删除该字符。如果有人将“空白”替换为需要的内容,这将是一个很大的帮助Python Tkinter:删除字符串的最后一个字符,python,tkinter,tkinter-entry,Python,Tkinter,Tkinter Entry,我正在做一个只允许输入数字的条目。如果输入的字符不是一个整数,我目前无法删除该字符。如果有人将“空白”替换为需要的内容,这将是一个很大的帮助 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("<Key
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()
将Tkinter作为tk导入
类别测试(tk.tk):
定义初始化(自):
tk.tk.\uuuuu初始化(self)
self.e=tk.Entry(self)
self.e.pack()
self.e.bind(“,self.on_keyrease)
tk.mainloop()
钥匙释放时的def(自身,事件):
#检查字符串是否仅由整数组成
如果self.e.get().isdigit()==False:
self.e.delete(“BLANK”,“end”)#我需要用字符串的最后一个字符替换0
其他:
#打印整数字符串
打印self.e.get()
测试=测试()
您也可以将上面的行更改为:
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)
或:
很好地为我们提供了一个工作示例,这有助于加快这一过程。如果您正在进行数据验证,您应该使用条目小部件的内置功能,特别是
validatecommand
和validate
属性
有关如何使用这些心房肌的说明,请参见 如果有人按下ctrl-V并粘贴一个较长的字符串会怎么样?我想我应该找到一种方法来搜索字符串并删除任何不是数字的内容,尤其是IntegerEntry子类。我理解为什么-1会起作用,但出于某种原因它会删除整个字符串。你知道为什么吗?似乎tkinter将
-1
作为任何东西的“默认值”,因此你可能需要对它进行处理。您可以获取当前设置的字符串,去掉最后一个字符,然后将其放回小部件中,而不是像现在这样删除它。看看更新answer@TankorSmash:我建议你删除答案中不正确的部分。这只会在将来引起混乱。@StevenRumbalski支持你
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)