问题描述
我目前正在制作一个输入表单,需要一个输入框限制为 2 个字符.我该怎么做?
I am currently making an input form and need an entry box to be limited to 2 characters. How do I do this?
#Date+time day entry boxes
day_entry1=Entry(List1, bg="#282B2B", fg="white", width=2)
day_entry1.place(x=77, y=58)
推荐答案
我想您正在使用 Tkinter 创建图形界面.在这种情况下,解决方案是使用 StringVar().这就像一个字符串变量,但它们可以在更改时调用函数.所以这将是一个例子:
I suppose you are using Tkinter to create a graphical interface. This being the case the solution is to use StringVar(). This is like a string variable but they can call a fuction when they are changed. So this would be an example:
def limitSizeDay(*args):
value = dayValue.get()
if len(value) > 2: dayValue.set(value[:2])
dayValue = StringVar()
dayValue.trace('w', limitSizeDay)
day_entry1=Entry(List1, bg="#282B2B", fg="white", width=2, textvariable=dayValue)
day_entry1.place(x=77, y=58)
所以基本上你创建一个函数来读取和检查天值的长度.此函数称为 limitSizeDay.然后定义一个名为 dayValue 的 StringVar 实例.您将一个函数绑定"(调用跟踪方法)到 dayValue,它会在内容更改时触发.最后,当您创建 Entry 小部件时,设置 textvariable=dayValue.这会将 dayValue 绑定到小部件,这基本上使 dayValue 存储条目中写入的任何内容.
So basically you create a function that reads and checks the length of the day value. This function is called limitSizeDay. Then you define a StringVar instance called dayValue. You 'bind' (call trace method) a function to dayValue which fires up when the contents are changed. And lastly when you create the Entry widget set textvariable=dayValue. This will bind the dayValue to the widget which basically makes dayValue to store any content written in the entry.
希望这能解决它并解释一些关于 StringVar 类的概念.
Hope this solves it and explains some concepts about StringVar class.
这篇关于(Python) 如何将输入框限制为最多 2 个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!