Is it possible, in Tkinter, to break up to the callback on a button. I have a segment of code that, if the user makes a mistake, will cause an error in a specific part of it, however it is within a for loop nested in another for loop and a while loop and can be either 2 or 3 functions deep (with the return of these functions being operated on).
What I would like to do would be to return to the mainloop() when this error is found.
So the code looks a bit like:
from Tkinter import *
def func_call(val_list):
y = []
for nn in range(len(val_list)):
if val_list[nn] < 0:
print('You entered a value that was too low.')
break
else:
y.append(val_list[nn]+5)
return(y)
def Button_callback(value):
val_list = [value,value-1,value-2,value-3]
y = func_call(val_list)
for nn in range(len(val_list)):
print(y[nn])
root = Tk()
Button(root,text='Press me',command=lambda: Button_callback(1)).grid(row=0,column=0)
root.mainloop()
What this does is identifies that the value is too low, and then breaks out the for loop and then returns the variable “y” to the previous function, which then promptly puts out an error because it expects “y” to be the same length as “val_list”.
What I would like it to do is to effectively return to the button press, so break out of both “func_call” and “Button_callback” with only “You entered a value that was too low.” as an error message.
Any suggestions?
This problem doesn’t have much to do with Tkinter, it’s just a normal control-flow question. Typically, the way you handle a situation like this where you want an inner function to stop all processing is to throw an exception, since an exception will propagate up until something catches it.
For example: