【问题标题】:Python Tkinter: Delete the Last Character of a StringPython Tkinter:删除字符串的最后一个字符
【发布时间】:2012-07-07 11:30:13
【问题描述】:

我正在输入一个只允许输入数字的条目。如果该字符不是整数,我目前坚持删除刚刚输入的字符。如果有人将“空白”替换为需要进入的内容,那将有很大帮助。

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()

【问题讨论】:

  • 如果有人按 ctrl-V 并粘贴更长的字符串怎么办?
  • 我想我应该找到一种方法然后搜索字符串并删除任何不是数字的东西
  • 参见A Validating Entry Widget,尤其是 IntegerEntry 子类。

标签: python tkinter tkinter-entry


【解决方案1】:

您也可以将上面的行更改为:

    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 会起作用,但由于某种原因它会删除整个字符串。知道为什么吗?
  • 似乎 tkinter 将 -1 作为任何东西的“默认”,所以你可能不得不对它感到棘手。与其像现在一样删除它,您可以获取当前设置的字符串,删除最后一个字符,然后将其放回小部件中。看看更新答案
  • @TankorSmash:我建议您删除答案中不正确的部分。只会在未来造成混乱。
  • @StevenRumbalski 支持你
【解决方案2】:

如果您要进行数据验证,您应该使用条目小部件的内置功能,特别是 validatecommand 和 validate 属性。

有关如何使用这些属性的说明,请参阅this answer。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-15
    • 2010-12-20
    • 1970-01-01
    • 2013-07-29
    • 2017-08-19
    相关资源
    最近更新 更多