1

I'm writing a VERY simple incremental game in Python (final product will almost certainly be less than 5000 lines), and I've come to a problem. So far, all the currency is added solely by clicking, but the next upgrade I'm adding is going to add a certain number to the main currency every second. It should be noted that I'm using Tkinter with Python for this, so my variables are all IntVar()'s. If I have the current currency set to 500, and the cps (currency per second) to 1, how do I add 1 to my currency = IntVar() every second?

currency = IntVar()
currency.set(500)
cps = IntVar()
cps.set(1)

I'm also assuming (possibly incorrectly) that it'll be a while loop and that I'll probably have import time and time.sleep(1) in there somewhere. Any help is much appreciated!

4
  • 2
    time.sleep() is not reliable. It may sleep for longer than you ask, or wake up early. On consumer grade hardware, you should be prepared to deal with (at least) hundreds of milliseconds of error. This will become more pronounced the more CPU-intensive programs you have running. Commented Feb 7, 2015 at 23:19
  • 1
    You're clearly using Tkinter so why not the after method of Tk widgets. Commented Feb 7, 2015 at 23:35
  • @Kevin I didn't know that, thank you. @Malik Brahimi I've never heard of after, for some reason... Commented Feb 8, 2015 at 1:13
  • I also feel obliged to warn you that timing in general is not reliable on most consumer-grade hardware/operating systems. The only way around this is real-time scheduling, which is an excellent way to lock up the entire OS if you make a mistake. Commented Feb 8, 2015 at 3:22

1 Answer 1

4

Let's assume you have a variable root as your main window:

def every_second():
    global currency, cps, root
    currency.set(currency.get() + cps.get())
    root.after(1000, every_second)

root.after(1000, every_second)
root.mainloop()
Sign up to request clarification or add additional context in comments.

2 Comments

This is exactly what I was looking for! Does it work if I change the value of cps with a button or something?
You can do as you please. The method is bound to the window and is recursively called every second. Be sure to mark as answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.