How do I make my function to run every second in python? [duplicate]Posted: - Source : stackoverflow
- mkrieger1 @mkrieger1May 19 at 11:41
You've got a function increasemoney which seems to do precisely this. Why can't you use it?
- Ev. Kounis @ev-kounisMay 19 at 11:43
You do not really need to post all that code to ask how to run a function once every second. The answer to the latter would be by using sleep(1) imported from the time module
- PM 2Ring @pm-2ringMay 19 at 12:02
@Ev.Kounis It's generally not a good idea to call time.sleep in an event-driven GUI loop because that freezes the loop. So such GUI frameworks provide other ways of requesting delays; the usual way in Tkinter is to call a widget's .after method, as illustrated in Right leg's answer.
- this answer @aMay 19 at 12:35
You may find the code in this answer helpful.
To make a function run every second in a tkinter app, use
after(delay_ms, callback=None, *args)
Registers an alarm callback that is called after a given time.
This method should be called at the end of the function that is to be periodically called. For instance, imagine a
MyWidgetclass whose I want to run the
foomethod every second:
class MyWidget(tk.Widget): def foo(self): print("foo") self.after(1000, self.foo)
- Right leg @right-legMay 19 at 12:29
@PM2Ring You're right, I edited it :)
- PM 2Ring @pm-2ringMay 19 at 12:32
That's better! Pity I can't give you another upvote. ;) I've been looking for a good canonical question to use as a dupe-target for this one, but I'm not having much luck.
- stackoverflow.com/questions/25753632/… @questionsMay 19 at 12:39
@PM2Ring Well, stackoverflow.com/questions/25753632/… surely says it all, but isn't quite canonical. I would make one, but I probably would be flagged as a dupe ^^ Will give it a shot though, since it looks like it might be useful
- PM 2Ring @pm-2ringMay 19 at 12:47
Yeah, that one was among the first that I looked at, but I decided it wasn't a great match because the OP already knew about .after, they just weren't using it properly. If you want to make a canonical as a self-answered question, make sure that the question properly conforms to the SO standard, and you should be ok, although you may want to add a comment explaining that it's for a canonical question. Ping me when it's done, either here or in the Python Chat room.
- stackoverflow.com/questions/44085554/… @questionsMay 20 at 12:00
@PM2Ring I posted a canonical Q/A on this topic: stackoverflow.com/questions/44085554/…