Search code examples
pythonmultithreadingtkintertimewhile-loop

Python, clicker game, coding of "passive income" , problems with Threading and time.sleep functions


I am trying to code a clicker game and already have a screen, a button to increase money and a upgrade to increase the money made with clicks. The whole thing is made in Tkinter. The next function i am now wanting to code is the passive income function for upgrades, which gives x money for every y seconds

def passive_income(moneygive,seconds):
    global money
    if True:
        money += moneygive
        time.sleep(seconds)

The problem with this is that it stops/delays the mainloop of the game while the time.sleep function, which is why i tried threading it

thread = threading.Thread(passive_income(10,10))
thread.start()
#before mainloop 

However this doesnt change anything and the thread also doesnt repeat. When i change the if statement to a while loop, the mainloop wont start. How can i code it so that, it doesnt break the mainloop? Thanks in advance


Solution

  • You are invoking the Thread constructor with the result of passive_income(10,10)(which makes the main thread wait for 10 seconds) while from the question it seems that you want the thread to execute that. You will have to pass in a lambda (or another executable construct) like so:

    threading.Thread(target= (lambda: passive_income(10,10)))
    

    This prepares a thread that will execute passive_income(10,10) when you start it and will immediately return control to the main thread after thread.start()

    You could also check:

    1. https://docs.python.org/3/library/threading.html
    2. https://docs.quantifiedcode.com/python-anti-patterns/correctness/assigning_a_lambda_to_a_variable.html