In my program, I have a block of code like this:
def engine_input_number_of_students_and_student_information(self, window):
self.__input.input_number_of_students(self, window)
print(self.number_of_students)
and the function input_number_of_students()
was defined in class Input as below:
class Input:
# Function to ask user to input number of student.
# Print error and force the user to re-input if wrong data is given.
def input_number_of_students(self, engine, window):
sub = tk.Toplevel(master=window)
sub.title("Number of students")
sub.resizable(height=False, width=False)
window.eval(f'tk::PlaceWindow {str(sub)} center')
frm1 = tk.Frame(master=sub)
frm1.grid(row=0, column=0, padx=10, pady=10)
lbl = tk.Label(text="Enter number of students:", master=frm1)
number_of_students_var = tk.StringVar()
ent = tk.Entry(width=3, master=frm1, textvariable=number_of_students_var)
lbl.grid(row=0, column=0, padx=5)
ent.grid(row=0, column=1, padx=5)
frm2 = tk.Frame(master=sub)
frm2.grid(row=1, column=0, sticky="nsew", padx=5, pady=5)
def ok():
try:
number_of_students = int(number_of_students_var.get())
if number_of_students < 0:
messagebox.showerror(message="Error: number of students must be non-negative")
ent.delete(-1, tk.END)
else:
engine.number_of_students = number_of_students
sub.destroy()
except:
messagebox.showerror(message="Invalid number of students")
ok_btn = tk.Button(text="OK", master=frm2, command=lambda: ok)
ok_btn.pack(ipadx=5)
ok_btn.wait_variable(number_of_students_var)
which basically create a sub-window with an entry and a button OK. The user input the value in the entry, and press OK, that value will be stored in engine.number_of_students
. But when I try to run this, function print(self.number_of_students)
was executed right when I input some value in the entry and I didn't even press the button (it prints 0, obviously).
I also tried to replace number_of_students_var
by engine.number_of_students
, it stucks there forever!
Well I read that the wait_variable()
will wait until the value of the parameter we pass into it is modified, then carry out the function, so the problem I'm having is... kinda make sense. But I feel that I don't truly understand this function and how to use it properly (like, what will wait for the modification of the parameter?) , so could you propose other ways to perform what I have described?