本文介绍了Tkinter 输入字符限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想在 TKinter 输入框中允许一个字符.我该怎么做?

I only want to allow one character in a TKinter Entry box. How should I do that?

推荐答案

5 年后的我来了 :)

Here I am 5 years later :)

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()) > 0:
        entry_text.set(entry_text.get()[-1])

entry_text.trace("w", lambda *args: character_limit(entry_text))

你可以改变这行代码:entry_text.set(entry_text.get()[-1])改变方括号中的索引来改变范围

you can change this line of code: entry_text.set(entry_text.get()[-1])change the index in the square brackets to change the range

例如:entry_text.set(entry_text.get()[:5]) 前 5 个字符限制entry_text.set(entry_text.get()[-5:]) 最后 5 个字符限制entry_text.set(entry_text.get()[:1]) 仅第一个字符entry_text.set(entry_text.get()[:-1]) 仅最后一个字符

For example:entry_text.set(entry_text.get()[:5]) first 5 characters limitentry_text.set(entry_text.get()[-5:]) last 5 characters limitentry_text.set(entry_text.get()[:1]) first character onlyentry_text.set(entry_text.get()[:-1]) last character only

这篇关于Tkinter 输入字符限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:12