weixin_46296502 2023-01-01 20:24 采纳率: 50%
浏览 83
已结题

Python输入框如何限制字符串长度

在编写一个登陆窗口时想要限制输入字符串的长度,但是想到的办法无法在输入时限制,只能输入完之后实现删除。
我目前的办法是在输入完之后,使用按钮删除多余的字符串,代码如下
# 删除输入框
def delete(self):
    self.text1.delete(5, 'end')
    self.text2.delete(10, 'end')
    self.code.delete(6, 'end')
全文代码:

import random
from tkinter import *
from tkinter.messagebox import showerror, showwarning, showinfo

from ttkbootstrap import Style
import ttkbootstrap as ttk
from FileMag import *

class log_in:

def __init__(self):
    # --------------------------------------------------------------------------------
    # 创建根窗口
    width = 300
    height = 200
    self.Login_window = tkinter.Tk()
    self.style = Style(theme='newtheme')
    self.Login_window = self.style.master
    self.screenwidth = self.Login_window.winfo_screenwidth()
    self.screenheight = self.Login_window.winfo_screenheight()
    self.Login_window.title("登录界面")
    self.Login_window.resizable(False, False)
    self.Login_window.geometry('%dx%d+%d+%d' % (width, height, (self.screenwidth - width) / 2, (self.screenheight -
                                                                                                height) / 2 - 50))
    self.Login_window.iconbitmap('./data/LGD1.ico')  # 窗口图标
    self.image1 = PhotoImage(file=r'./data/eye.gif')  # 显示按钮图标
    # --------------------------------------------------------------------------------
    # 设置用户账号输入框
    self.ID = ttk.Label(self.Login_window, text="账号:", font=('Modern', 12), style="primary")
    self.ID.place(relx=0.23, rely=0.2, anchor=CENTER)
    self.text1 = ttk.Entry(self.Login_window, font=('黑体', 15), width=2, style="primary")
    self.text1.place(relx=0.55, rely=0.2, anchor=CENTER, width=150, height=30)
    # --------------------------------------------------------------------------------
    # 设置用户密码码输入框
    self.password = ttk.Label(self.Login_window, text="密码:", font=('Modern', 12), style="primary")
    self.password.place(relx=0.23, rely=0.4, anchor=CENTER)
    self.text2 = ttk.Entry(self.Login_window, font=('黑体', 15), show='*', width=1, style="primary")
    self.text2.place(relx=0.55, rely=0.4, anchor=CENTER, width=150, height=30)
    self.show = ttk.Button(command=lambda: [self.myfunc(), self.delete()], image=self.image1, width=15,
                           style="disabled-link")
    self.show.place(relx=0.73, rely=0.4, anchor=CENTER)
    # --------------------------------------------------------------------------------
    # 设置验证码输入框
    self.code = ttk.Label(self.Login_window, text="验证码:", font=('Modern', 12), style="primary")
    self.code.place(relx=0.25, rely=0.6, anchor=CENTER)
    self.code = ttk.Entry(self.Login_window, font=('黑体', 15), width=2, style="primary")
    self.code.place(relx=0.48, rely=0.6, anchor=CENTER, width=80, height=30)
    # --------------------------------------------------------------------------------
    # 设置获取验证码的按钮
    # 生成验证码列表
    self.list_b = []
    self.list1 = []
    for i in range(0, 10):
        self.list1.append(i)
    for j in range(65, 91):
        self.list1.append(chr(j))
    for k in range(97, 123):
        self.list1.append(chr(k))
    self.txt = StringVar()
    self.txt.set("验证码")
    self.codeStr = ttk.Button(self.Login_window, textvariable=self.txt, command=lambda: [self.create_authcode(),
                                                                                         self.delete()],
                              )
    self.codeStr.place(relx=0.74, rely=0.6, anchor=CENTER)
    # --------------------------------------------------------------------------------
    # 设置登录按钮
    self.enter = ttk.Button(self.Login_window, text="登录", command=lambda: self.login_check(),
                            )
    self.enter.place(relx=0.3, rely=0.8, anchor=CENTER)
    self.esc = ttk.Button(self.Login_window, text="退出", command=lambda: self.quit_())
    self.esc.place(relx=0.7, rely=0.8, anchor=CENTER)
    self.Login_window.mainloop()
    # 获取输入框内容

# 登陆后关闭窗口
def login_check(self):
    name = self.text1.get()
    secret = self.text2.get()
    verification_code = self.code.get()
    if len(name) != 0:
        if len(secret) != 0:
            if len(self.list_b) == 0:
                showinfo(title='警告', message='请刷新验证码')
            else:
                if len(verification_code) == 0:
                    showwarning(title='警告', message='请输入验证码')
                else:
                    num_a = self.list_b[0]
                    if verification_code == num_a:
                        if name == 'W' and secret == '1':
                            self.Login_window.destroy()
                            Filemanager()
                        else:
                            showerror(title='错误', message='账号或密码错误!')

                    else:
                        showerror(title='错误', message='验证码错误')
        else:
            showwarning(title='警告', message='请输入密码')

    else:
        showwarning(title='警告', message='请输入用户名')

# 退出按钮关闭窗口
def quit_(self):
    self.Login_window.destroy()

# 显示密码
def myfunc(self):

    if self.text2.cget("show") == "*":
        self.text2.configure(show="")
    elif self.text2.cget("show") == "":
        self.text2.configure(show="*")

# 定义函数,功能为生成有大写字母、小写字母、数字组成的6位随机验证码
def create_authcode(self):
    name = self.text1.get()
    secret = self.text2.get()
    if len(name) != 0:
        if len(secret) != 0:
            self.list_b.clear()
            num = random.sample(self.list1, 6)
            s = "".join("%s" % id1 for id1 in num)
            self.list_b.append(s)
            self.txt.set(s)

        else:
            showwarning(title='警告', message='请输入密码')

    else:
        showwarning(title='警告', message='请输入用户名')

# 删除输入框
def delete(self):
    self.text1.delete(5, 'end')
    self.text2.delete(10, 'end')
    self.code.delete(6, 'end')

if name == 'main':
app = log_in()

主要想实现在输入时限制,只能输入一定长度的字符串,希望大家解决。
  • 写回答

2条回答 默认 最新

  • Ko-walski 2023-01-01 20:59
    关注

    参考这个

    from tkinter import *
    
    Window = Tk()
    Window.geometry("200x200+50+50") # heightxwidth+x+y
    
    mainPanel = Canvas(Window, width = 200, height = 200) # main screen
    mainPanel.pack()
    
    entry_text = StringVar() # the text in  your entry
    entry_widget = Entry(mainPanel, width = 20, textvariable = entry_text) # the entry
    mainPanel.create_window(100, 100, window = entry_widget)
    
    def character_limit(entry_text):
        if len(entry_text.get()) > 10:
            entry_text.set(entry_text.get()[:10])
    
    entry_text.trace("w", lambda *args: character_limit(entry_text))
    
    Window.mainloop()
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 1月1日
  • 已采纳回答 1月1日
  • 创建了问题 1月1日

悬赏问题

  • ¥15 数学建模数学建模需要
  • ¥20 Java Sound Api 调用Mixer.getLine偶现Line unsupported错误。
  • ¥15 使用cuda加速opencv运算但是报错AttributeError: module 'cv2.cuda' has no attribute 'getCudaEnabledDeviceCount'
  • ¥15 java输入输出异常
  • ¥15 三子连珠对弈小游戏制作
  • ¥15 C++扑克牌游戏的编程
  • ¥15 有人能看一下我宿舍管理系统的报修功能该怎么改啊?链表那里总是越界
  • ¥15 cs loadimage运行不了,easyx也下了,没有用
  • ¥15 r包runway详细安装教程
  • ¥15 Html中读取Json文件中数据并制作表格