在 python 中的文本之间按一定长度输入特殊字符

发布于 2025-01-20 11:28:21 字数 1284 浏览 2 评论 0原文

代码在主项目中运行良好,从中获取了一些示例代码,因为下面的

from tkinter import *

root = Tk()
root.geometry('200x200')
root.title('Testing')
num1 = StringVar()
num2 = StringVar()

def callback(integer):
    if integer.isdigit():
        return True
    elif integer == "":
        return True
    else:
        return False

def limit_no1(no):
    c = no.get()[0:16]
    no.set(c)

num1.trace("w", lambda name, index, mode, sv=num1: limit_no1(sv))
reg = root.register(callback)
ent1 = Entry(root, textvariable=num1)
ent1.pack()
ent1.config(validate="key", validatecommand=(reg, '%P'))

条件仅接受数字,并增加16位数字 但是就像某些Web应用程序一样,我需要4个字符后的间距 是否有任何方法,以便我可以应用于此,并以“”为“”,在BTW数据中,

我对某些代码进行了工作,但是在索引索引

以下代码时,请索引以下代码。

num2.trace("w", lambda name, index, mode, sv=num2: limit_no2(sv))
ent2 = Entry(root, textvariable=num2)
ent2.pack(pady=20)
ent2.config(validate="key", validatecommand=(reg, '%P'))

def limit_no2(no):
    c = no.get()[0:19]
    split_string = [c[i:i + 4] for i in range(0, len(c), 4)]
    if len(split_string) > 1:
        final_string = ''
        for i in range(len(split_string)):
            final_string += split_string[i]
            final_string += " "
        no.set(final_string)
    else:
        no.set(c)

root.mainloop()

code is running good in main project , took some sample code from that as below

from tkinter import *

root = Tk()
root.geometry('200x200')
root.title('Testing')
num1 = StringVar()
num2 = StringVar()

def callback(integer):
    if integer.isdigit():
        return True
    elif integer == "":
        return True
    else:
        return False

def limit_no1(no):
    c = no.get()[0:16]
    no.set(c)

num1.trace("w", lambda name, index, mode, sv=num1: limit_no1(sv))
reg = root.register(callback)
ent1 = Entry(root, textvariable=num1)
ent1.pack()
ent1.config(validate="key", validatecommand=(reg, '%P'))

this has some condition as accepting only numbers and up 16 digits
but as like some web apps i need spacing after 4 characters
is there any method for that so that i can apply to this and and for input of currency also as ',' in btw data

I worked on some code but indexing getting issue in indexing

the below code continuation of above only

num2.trace("w", lambda name, index, mode, sv=num2: limit_no2(sv))
ent2 = Entry(root, textvariable=num2)
ent2.pack(pady=20)
ent2.config(validate="key", validatecommand=(reg, '%P'))

def limit_no2(no):
    c = no.get()[0:19]
    split_string = [c[i:i + 4] for i in range(0, len(c), 4)]
    if len(split_string) > 1:
        final_string = ''
        for i in range(len(split_string)):
            final_string += split_string[i]
            final_string += " "
        no.set(final_string)
    else:
        no.set(c)

root.mainloop()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文