限制 Entry 中的字符数。

huangapple go评论61阅读模式
英文:

How to limit the character in Entry

问题

我需要将输入限制为最多5位数字

```python
def validate(S):
    try:
        float(S)
        return True
    except ValueError:
        messagebox.showerror(message="数据错误,仅限数字。", title="错误")
        return False

e1 = tk.Entry(master, validate="key", validatecommand=(master.register(validate), '%S'))

我有这个方法来接收和验证输入,但我想知道如何在输入上设置最多5位数字的限制。

我尝试过使用此问题中使用的方法(https://stackoverflow.com/questions/5446553/tkinter-entry-character-limit),但在validate方法中不起作用。


<details>
<summary>英文:</summary>

I need to limit the entry to a maximum of 5 digits.

def validate(S):
try:
float(S)
return True
except ValueError:
messagebox.showerror(message="Datos erroneos, únicamente números.", title="ERROR")
return False

e1 = tk.Entry(master, validate="key", validatecommand=(master.register(validate), '%S'))


I have this method to receive and validate that it&#39;s just numbers at the entry, but i would like to know how can I put a max limit of 5 digits on the entry.

I tried with the methods used in this question (https://stackoverflow.com/questions/5446553/tkinter-entry-character-limit) but it is not working with the validate method.



</details>


# 答案1
**得分**: 3

从validate函数中返回False,如果字符串的长度超过5。

```python
def validate(S):
    try:
        float(S)
        return len(S) <= 5
    except ValueError:
        messagebox.showerror(message="Datos erroneos, únicamente números.", title="ERROR")
        return False
英文:

Return False from validate if the length of the string is more than 5.

def validate(S):
    try:
        float(S)
        return len(S) &lt;= 5
    except ValueError:
        messagebox.showerror(message=&quot;Datos erroneos, &#250;nicamente n&#250;meros.&quot;, title=&quot;ERROR&quot;)
        return False

huangapple
  • 本文由 发表于 2023年2月14日 00:07:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75438394.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定