英文:
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'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) <= 5
except ValueError:
messagebox.showerror(message="Datos erroneos, únicamente números.", title="ERROR")
return False
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论