Search code examples
pythontkinterreturn

Python not waiting for return function, and continuing without a response


I have a function that saves files to the user's computer in Tkinter. I am trying to create a prompt for the user if they are trying to save a file that already exists, asking them if they'd like to overwrite the existing file, or not. I'm not going to include the whole code as it is 3000+ lines, but an example of what I'm trying to do:

I understand os.path.save() is not valid, I'm using Shutil to copy an existing file from another location, this is just for example purposes.

def overWritePrompt():
    promptFrame = tk.Frame(maniWin, bg=_blk)
    promptFrame.place(relx=.4,rely=.2,relheight=.1,relwidth=.2)

    promptHead = tk.Label(promptFrame, bg=_blk, fg=_wht, text="Overwrite existing route?")
    promptHead.place(relx=0,rely=0,relheight=.4,relwidth=1)
    
    promptYes = tk.Button(promptFrame, bg=_dgrn, fg=_wht, text="Yes", relief="sunken", activebackground=_dgrn, activeforeground=_wht, command=lambda:(selection(True)), borderwidth=0)
    promptYes.place(relx=.1,rely=.5,relheight=.4,relwidth=.35)
    
    promptNo = tk.Button(promptFrame, bg=_red, fg=_wht, text="No", relief="sunken", activebackground=_red, activeforeground=_wht, command=lambda:(selection(False)), borderwidth=0)
    promptNo.place(relx=.45,rely=.5,relheight=.4,relwidth=.35)

    def selection(response):
        promptFrame.destroy()
        return response

def saveFile(fileName):
    overwrite = False
    if os.path.exists(os.path.join(directory, fileName)):
        overwrite = overwritePrompt()
    if overwrite:
        os.path.remove(fileName)
        os.path.save(fileName) 
    else:
        os.path.save(fileName)

I expect this to display the prompt to the user and wait for a response before continuing to the saving portion, however it just immediately returns None for the overwrite bool, and continues on with the rest of the code.

Why isn't overwrite = overwritePrompt() waiting for overWritePrompt() to return before continuing?

I have tried adding while loops in different places to keep the code from moving on until the user inputs their answer, but that just freezes the app completely.


Solution

  • The nested function selection() doesn't iteract with the outer function overwritePrompt at all so its return statement doesn't affect the value returned by the outer function. selection() is just a normal function like any other in that regard.

    You could simplify the whole thing by using a built-in Tk message box:

    def saveFile(fileName):
        if os.path.exists(os.path.join(directory, fileName)):
            overwrite = tkinter.messagebox.askokcancel("Confirm", "Overwrite file?")
            if overwrite:
                os.path.remove(fileName)
        os.path.save(fileName)