简体   繁体   中英

how to make a python script run repeatedly

I have a simple script which saves some values to a database , I also have a window built in Tkinter. So basically my problem is I want the savebase() function to be continuously called upon, till the window remains open. How can this be done ?

Till now I'm able just to run the function only once, when the window opens itself. I can also put a button to repeat it , but it doesn't solve the purpose as i want this thing to be done like 2 times per second.

A simplified version of my attempt at this is like :

     import Tkinter
     import saveDB

     def doing_it():
          a = saveDB.save()
          a.savebase()

     window = Tkinter.Tk()
     window.title("Saving Database")
     window.geometry("300x300+100+100")


     first_button=Tkinter.Button(window, text='Save DB', command=doing_it,
                                fg='white', bg='black').grid(row=3,column=2)

     window.mainloop()

is if name == main() , the way to do it ? during my search for the above mentioned problem, I came across it , though i know nothing about it.

Use the after -method:

def doing_it():
     a = saveDB.save()
     a.savebase()
     window.after(500, doing_it)

 window = Tkinter.Tk()
 window.title("Saving Database")
 window.geometry("300x300+100+100")
 window.after(500, doing_it)
 window.mainloop()

You had a follow up question in a commment, and I don't have enough rep to comment, so I'll leave this here.

You said you were assigning the text to a label, but it was not updating. I'm not 100% sure what you mean, but here's a working example of what I'm doing that should work for you as well.

#! /usr/bin/env python3.4
from tkinter import *
import time

GLOBVAR = 0
class App(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.geometry("300x300+500+200")
        self.wm_title("Test update label")
        self.label = Label(text="you  won't see this")
        self.label.pack(pady = (150, 0)) 
        self.update_clock()

    def update_clock(self):
        global GLOBVAR
        GLOBVAR += 1
        self.label.configure(text = GLOBVAR)
        self.after(1000, self.update_clock)

app=App()
app.mainloop()

In this case, the key part that updates the label widget is the self.label.configure() call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM