Tkinter - 创建动态条目小部件

我找不到以下问题的解决方案。a给定的是一个带有 4 个入口小部件, bc,的 tkinter 应用程序,d它必须满足以下条件:

条目中只能输入数字a,且不得超过 4 位数字

如果a为空则无法在 中进行输入cc和的内容d与 相同b

如果a不为空,则可以在 中进行输入cc和的内容d相同(它们与 未链接b)。

当前的解决方案仅部分起作用。它能够链接条目bc取消链接它们。但我不知道如何包含 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 False


callback = root.register(only_numeric_input)  # registers a Tcl to Python callback


var_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 entrys

entry_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 validation


mainloop()


精慕HU
浏览 102回答 1
1回答

繁星点点滴滴

给你。您正在使用isdigitfor Pbut%P是整个文本(包括刚刚按下的内容),所以我们切换到isnumeric. 如果我正确理解了你的指示,你就忘了处理entry_d.我用 arange而不是len(P) > 0 and len(P) < 5,而且range是正确的。def only_numeric_input(P):&nbsp; &nbsp; if len(P) in range(1,5) and P.isnumeric():&nbsp; &nbsp; &nbsp; &nbsp; #if we have 1 to 4 numeric characters&nbsp; &nbsp; &nbsp; &nbsp; # enable entry_c, and unlink entry c & d content from entry b&nbsp; &nbsp; &nbsp; &nbsp; entry_c.config(textvariable=var_c, state='normal')&nbsp; &nbsp; &nbsp; &nbsp; entry_d.config(textvariable=var_c)&nbsp; &nbsp; elif not P:&nbsp; &nbsp; &nbsp; &nbsp; #if we have no characters&nbsp; &nbsp; &nbsp; &nbsp; # disable entry_c, and link entry c & d content to entry b&nbsp; &nbsp; &nbsp; &nbsp; entry_c.config(textvariable=var_b, state='disabled')&nbsp; &nbsp; &nbsp; &nbsp; entry_d.config(textvariable=var_b)&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; #everything else&nbsp; &nbsp; &nbsp; &nbsp; return False&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return True
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python