How to run a function in the background of tkinter

后端 未结 5 2131
独厮守ぢ
独厮守ぢ 2021-01-04 21:48

I am new to GUI programming and I want to write a Python program with tkinter. All I want it to do is run a simple function in the background that can be influenced through

5条回答
  •  太阳男子
    2021-01-04 22:08

    Event based programming is conceptually simple. Just imagine that at the end of your program file is a simple infinite loop:

    while :
        
        
    

    So, all you need to do to run some small task continually is break it down into bite-sized pieces and place those pieces on the event queue. Each time through the loop the next iteration of your calculation will be performed automatically.

    You can place objects on the event queue with the after method. So, create a method that increments the number, then reschedules itself to run a few milliseconds later. It would look something like:

    def add_one(self):
        self.counter += 1
        self.after(1000, self.add_one)
    

    The above will update the counter once a second. When your program initializes you call it once, and from then after it causes itself to be called again and again, etc.

    This method only works if you can break your large problem (in your case "count forever") into small steps ("add one"). If you are doing something like a slow database query or huge computation this technique won't necessarily work.

提交回复
热议问题