I cannot find a solution to the following problem. Given is a tkinter application with 4 entry widgets a,b,c, and d that must fulfill the following conditions:
Only numbers may be entered in entry a and there must not be more than 4 digits
If a is empty then no input can be made in c. The contents of c and d are the same as b.
If a is not empty then an entry can be made in c. The content of c and d is the same (they are unlinked from b).
The current solutions works only partially. It is able to link entry b and c and unlink them. But I don't know how to include the 3 condition.
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()
Entrys — it sounds to me that you want to do validation of what is being entered into them. The good news is tkinterEntrywidgets support validation. Here's some slightly dated documentation (I suspect you may be able to find other sources now that you now know what term to look for).'key'triggers a call to the callback function (as well as various other events mentioned in the documentation)."%S"code.