Exit Function Into Main Code

Question:

I am trying to build a gambling dice game for fun using Python’s Tkinter in Python 3. The error I am having is after the money is taken away from your bank account (it does this in a different function) I want it to go back to the mainloop. So basically I want to exit a function to get back into the main code (which isn’t in a function). Any ideas on how?

Asked By: Caden Grey

||

Answers:

The function will automatically stop when it is finished running. Using return, though, will immediately exit the current function, perhaps before it gets through all of its code, if that’s what you mean.

Answered By: Luke B

I am not 100% sure what your problem is but it sounds like you might not fully understand how a function works.

In a tkinter application the mainloop() is always looping so once your function has finished the the next task in that loop will run and if no more task are scheduled in that loop the loop will reset.

Take this below code for example.

from tkinter import *

root = Tk()

def some_function():
    print("this function just ran")

Button(root, text="Run some func", command = some_function).pack()

root.mainloop()

What we see is a button that allows us to call on some_function and then once that function is over we are “back in” the mainloop() so to speak.

There is nothing you need to do special here unless inside of your function you are running some kind of loop and want to end the loop on some criteria. Then you can use a break line to end that loop.

Answered By: Mike – SMT
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.