如何在python tkinter中限制字符条目?

如何在python tkinter中限制字符条目?,python,python-3.x,string,function,tkinter,Python,Python 3.x,String,Function,Tkinter,如果用户在输入框中输入类似“z”的内容,则不应在输入框中键入或显示,应立即将其删除 示例我想输入用户名,但用户名之间不应包含任何空格,如果键入空格,则不应在输入框中显示 这是我的密码 import tkinter as tk window = tk.Tk() window['bg'] = 'black' window.rowconfigure([0,1,2,3,4,5,6,7],weight=1) window.columnconfigure([0,1,2,3,4,5,6,7],weight=

如果用户在输入框中输入类似“z”的内容,则不应在输入框中键入或显示,应立即将其删除

示例我想输入用户名,但用户名之间不应包含任何空格,如果键入空格,则不应在输入框中显示

这是我的密码

import tkinter as tk

window = tk.Tk()
window['bg'] = 'black'
window.rowconfigure([0,1,2,3,4,5,6,7],weight=1)
window.columnconfigure([0,1,2,3,4,5,6,7],weight=1)

def checkspace(char):
        if ' ' or '\t' in list(clar):
            lbl_1['text'] = 'Username cannot\nHave space'

#____________________________________________________________________________________________

lbl_1 = tk.Label(text='welcome',font='consolas 25 bold',relief=tk.FLAT,borderwidth=3,
                 justify='center',width=20,height=7,bg=window['bg'],fg='white')
lbl_1.grid(row=0,column=0,pady=5,padx=10,rowspan=4,columnspan=5)

lbl_2 = tk.Label(text='Enter\nDetails',font='consolas 20 bold',
                 justify='center',bg=window['bg'],fg='white')
lbl_2.grid(row=0,column=6,pady=15,padx=5,columnspan=3,rowspan=1)

lbl_3 = tk.Label(text='USERNAME:',font='consolas 12 bold',
                 justify='center',bg=window['bg'],fg='white')
lbl_3.grid(row=2,column=6)

lbl_4 = tk.Label(text='PASSWORD:',font='consolas 12 bold',
                 justify='center',bg=window['bg'],fg='white')
lbl_4.grid(row=3,column=6)

ent_user = tk.Entry(justify='center',font='consolas 10 bold',fg='#1d1d1d',command=checkspace)
ent_user.grid(row=2,column=7,pady=10,padx=10)

ent_pass = tk.Entry(justify='center',font='consolas 10 bold',fg='#1d1d1d',show='●')
ent_pass.grid(row=3,column=7,pady=10,padx=10)

btn_signin = tk.Button(text='Next',font='consolas 8 bold',
                       width=6,borderwidth=2,bg='#2d89ef',fg='white',activeforeground='red')
btn_signin.grid(row=5,column=7,ipadx=2,ipady=2,padx=20,pady=10)

#____________________________________________________________________________________________
window.mainloop()


条目
具有可以执行此任务的
验证
验证命令

你的参赛作品应为:

ent_user = tk.Entry(justify='center',font='consolas 10 bold',fg='#1d1d1d')
ent_user.config(validate="key", validatecommand=(window.register(checkspace), '%P'))
def checkspace(char):
    return (len(char)>0 and not char[-1].isspace()) or char == ''
您的checkspace函数应该是:

ent_user = tk.Entry(justify='center',font='consolas 10 bold',fg='#1d1d1d')
ent_user.config(validate="key", validatecommand=(window.register(checkspace), '%P'))
def checkspace(char):
    return (len(char)>0 and not char[-1].isspace()) or char == ''