window = Tk() #create app window
#custom message box function
def answerMessagebox(returnValue, toplevel, functionName=""):
global answer
answer = returnValue
print("The answer variable is (inside answerMessagebox function): ", answer)
if functionName: #if there is a command do this
functionName()
toplevel.destroy() #close messagebox
def messageboxYesNo(title, text, functionName=""):
toplevel = Toplevel(window)
toplevel.title(title)
l1=Label(toplevel, image=iconQuestion)
l1.grid(row=0, column=0, pady=(7, 0), padx=(10, 30), sticky="e")
l2=Label(toplevel,text=text)
l2.grid(row=0, column=1, columnspan=3, pady=(7, 10), sticky="w")
b1=Button(toplevel,text="Yes",command=lambda: answerMessagebox(True, toplevel, functionName=functionName),width = 10)
b1.grid(row=1, column=1, padx=(2, 35), sticky="e")
b2=Button(toplevel,text="No",command= lambda: answerMessagebox(False, toplevel), width = 10)
b2.grid(row=1, column=2, padx=(2, 35), sticky="e")
def close_window():
driver.quit()
window.destroy()
exit()
exitButton = Button(window, text="Exit", command=lambda: messageboxYesNo("QUIT", "Are you sure you want to Quit?", functionName=close_window), font=breadtextFont, bg=button_color, fg=button_text_color) #add a exit button
exitButton.pack(side="top", anchor=NE, padx=15, pady=10)
window.mainloop()
The print
statement inside answerMessagebox
prints out correctly False
if I press No-button and True
if I press Yes-button. I want to use that answer inside another function and do logic based on the answer.
def foo():
global answer
answer = ""
messageboxYesNo("Submit report", "Are you sure you want to submit?") #expect global variable to change to True if press Yes-button. But it actually prints out nothing.
if answer:
#do something
Inside the foo()
function the global variable answer
does not change after I run the messageboxYesNo
function and therefore the if answer:
statements is not running.
Why is the global variable not changing? I guess it is because foo()
continues and is not waiting for messageboxYesNo
function to finish. How can I solve this issue?
I use a global variable because the command=
in tkinter cannot return anything from a function.