我怎样才能使进入widg的实时限制计数

2022-12-05 02:14:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须为我的密码输入字段设置一个实时限制计数器。我需要一个实时限制计数器计数的文本输入数

我用按钮找出输入字段的文本计数,但我希望它是实时的

我的代码

from tkinter import *

Root=Tk()
Entry1=Entry(Root)
length=len(Entry1.get())
Labellen=Label(Root,text= 
(length,"/10"),bg="black",fg="green")

def check():
    if len(Entry1.get())>10:
        length=len(Entry1.get())
        Labellen.configure(text=("you have reached maximum limit ", length , " /10"),fg="red")    
    else:
        length=len(Entry1.get())
        Labellen.config(text=(length,"/10"))

Entry1.configure(font=('MS Serif',10),bg="light 
blue",relief="groove",bd=15,
insertbackground="red",insertborderwidth=15)
Entry1.pack()

Labellen.pack()

Btn=Button(Root,text="check limit",command=check)
Btn.pack()

Root.mainloop()

Tags: text文本getlenconfigurecheck计数器rootlengthpack计数bgfgentry1labellen
1条回答
网友
1楼 · 发布于 2022-12-05 02:14:53

您可以使用tkinter Entryvalidatecommand参数来完成。有关更多详细信息,请查看docs

import tkinter as tk

root = tk.Tk()

def check(why):
    ctr.set(len(why))
    return True

count = root.register(check)
entry = tk.Entry(root, validate="key", validatecommand=(count, '%P'))
entry.grid(row=0, column=0, padx=10, pady=5)
entry.focus_set()

ctr = tk.StringVar()
ctr.set(0)
tk.Label(root, text='Counter: ').grid()
counter = tk.Label(root, textvariable=ctr, bg='white')
counter.grid()

root.mainloop()

enter image description here