如何解决Tkinter-创建动态条目小部件
我找不到以下问题的解决方案。给出了一个tkinter应用程序,该应用程序具有4个条目窗口小部件a
,b
,c
和d
,必须满足以下条件:
在条目a
中只能输入数字,并且不得超过4位数字
如果a
为空,则无法在c
中进行输入。 c
和d
的内容与b
相同。
如果a
不为空,则可以在c
中进行输入。 c
和d
的内容是相同的(它们与b
无关)。
当前解决方案仅部分起作用。它能够链接条目b
和c
并取消链接。但是我不知道如何包含这三个条件。
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,text="d").grid(row = 3,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,0))
entry_a.configure(validate="key",validatecommand=(callback,"%P")) # enables validation
mainloop()
解决方法
来吧。您将isdigit
用于P
,但是%P
是整个文本(包括刚刚按下的内容),因此我们切换到isnumeric
。如果我正确理解了您的说明,则您忘记处理entry_d
。
我使用了range
而不是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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。