Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
7.2k views
in Technique[技术] by (71.8m points)

python - How do I refresh window without .mainloop() function in Tkinter?

This is my code:

   import tkinter as tk
   import time
    
    screen = tk.Tk()
    normal_label = tk.Label()
    normal_label.pack()
    for i in range(1, 50):
        time.sleep(0.1)
        normal_label.configure(text=str(i))
    screen.mainloop()

If I run this the window doesn't appear until the timer has run out. What I want to happen is that a screen will appear that will count down. This is just an example of what I want to make, the real code is to big and needs to much context to show. How do I fix this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you are looking for the "after()" method in tkinter. I just built you a small example (please find it below). It is a ticking clock.

You can see there, that I use the "after()" method to call the function which accommodates it.

import tkinter as tk
from time import strftime


class MyClock(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        # store everything in a frame
        self.container = tk.Frame(self)
        self.container.pack(side="top", fill="both", expand=True)
        # build a clock
        self.clock = tk.Label(self, font=('calibri', 40, 'bold'), background='black', foreground='white')
        self.clock.grid(column=0, row=0, sticky='nsew', in_=self.container)
        self.clock.configure(text=strftime('%H:%M:%S'), height=2)
        # Start clock
        self.tick()

    def tick(self):
        self.after(1000, self.tick)  # <----------- this is the method you are looking for
        # update time shown on your clock label
        now_time = strftime('%H:%M:%S')
        self.clock.configure(text=now_time)


if __name__ == "__main__":
    app = MyClock()
    app.mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...