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!

Elle Nolan
  • 379
  • 5
  • 8
  • 22
  • 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. – Kevin Feb 07 '15 at 23:19
  • 1
    You're clearly using Tkinter so why not the `after` method of Tk widgets. – Malik Brahimi Feb 07 '15 at 23:35
  • @Kevin I didn't know that, thank you. @Malik Brahimi I've never heard of `after`, for some reason... – Elle Nolan Feb 08 '15 at 01:13
  • I also feel obliged to warn you that timing *in general* is [not reliable](http://stackoverflow.com/a/85149/1340389) 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. – Kevin Feb 08 '15 at 03:22

1 Answers1

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()
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
  • This is exactly what I was looking for! Does it work if I change the value of cps with a button or something? – Elle Nolan Feb 08 '15 at 01:27
  • 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. – Malik Brahimi Feb 08 '15 at 02:14