为了账号安全,请及时绑定邮箱和手机立即绑定

Tkinter - 创建动态条目小部件

Tkinter - 创建动态条目小部件

精慕HU 2023-06-06 16:24:35
我找不到以下问题的解决方案。a给定的是一个带有 4 个入口小部件, b, c,的 tkinter 应用程序,d它必须满足以下条件:条目中只能输入数字a,且不得超过 4 位数字如果a为空则无法在 中进行输入c。c和的内容d与 相同b。如果a不为空,则可以在 中进行输入c。c和的内容d相同(它们与 未链接b)。当前的解决方案仅部分起作用。它能够链接条目b和c取消链接它们。但我不知道如何包含 3 条件。from tkinter import *root = Tk()root.geometry("200x200")def only_numeric_input(P):    if len(P) > 0 and P.isdigit():        # enable entry_c and unlink its content from entry_b        entry_c.config(textvariable=" ", state='normal')    else:        # disable entry_c        entry_c.config(textvariable=var_b, state='disabled')    if len(P) > 4:        return False    # checks if entry's value is an integer or empty and returns an appropriate boolean    if P.isdigit() or P == "":  # if a digit was entered or nothing was entered        return True    return Falsecallback = root.register(only_numeric_input)  # registers a Tcl to Python callbackvar_b = StringVar()var_c = StringVar()Label(root, text="a").grid(row = 0, column = 0, pady = (10,0))Label(root, text="b").grid(row = 1, column = 0)Label(root, text="c").grid(row = 2, column = 0)Label(root, text="d").grid(row = 3, column = 0, pady = (40,0))entry_a = Entry(root)entry_b = Entry(root, textvariable = var_b)entry_c = Entry(root, textvariable = var_b, state = "disabled")entry_d = Entry(root, textvariable = var_b)#display entrysentry_a.grid(row = 0, column = 1)entry_b.grid(row = 1, column = 1)entry_c.grid(row = 2, column = 1)entry_d.grid(row = 3, column = 1, pady = (40,0))entry_a.configure(validate="key", validatecommand=(callback, "%P"))  # enables validationmainloop()
查看完整描述

1 回答

?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

给你。您正在使用isdigitfor Pbut%P是整个文本(包括刚刚按下的内容),所以我们切换到isnumeric. 如果我正确理解了你的指示,你就忘了处理entry_d.


我用 arange而不是len(P) > 0 and len(P) < 5,而且range是正确的。


def only_numeric_input(P):

    if len(P) in range(1,5) and P.isnumeric():

        #if we have 1 to 4 numeric characters

        # enable entry_c, and unlink entry c & d content from entry b

        entry_c.config(textvariable=var_c, state='normal')

        entry_d.config(textvariable=var_c)

    elif not P:

        #if we have no characters

        # disable entry_c, and link entry c & d content to entry b

        entry_c.config(textvariable=var_b, state='disabled')

        entry_d.config(textvariable=var_b)

    else:

        #everything else

        return False

    

    return True


查看完整回答
反对 回复 2023-06-06
  • 1 回答
  • 0 关注
  • 100 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信