Keep tkinter Progressbar running until a file is c

2019-08-08 21:03发布

I'm trying to put a info popup window to the user to advise him that a file is being created and that he must wait until it's created. I've a master frame that creates a popup window that shows the Progressbar with a message. This popupwindow must be destroyed as soon as the file has been created on the system.

This is my try:

import os
from Tkinter import *
import ttk

class UI(Frame):
    def __init__(self,master):
        Frame.__init__(self, master)
        self.master = master
        self.initUI()

    def initUI(self):
        popup = Toplevel(self)
        txt = Label(popup, text="Please wait until the file is created").grid(row=0, column=0)
        progressbar = ttk.Progressbar(popup, orient=HORIZONTAL, length=200, mode='indeterminate')
        progressbar.grid(row=1, column=0)
        progressbar.start()

        self.checkfile()

        progressbar.stop()
        popup.destroy()

    def checkfile(self):
        while os.path.exists("myfile.txt") == False:
            print "not created yet"

if __name__ == "__main__":
    root = Tk()
    aplicacion = UI(root)
    root.mainloop()

The problem is that the UI get's freezed and I can't see any window. I think I must use Threads to solve this problem right? Do I've to make two threads, one for the UI and the other one for the checkfile function, or with one is enough?

It would be highly appreciated if someone could add the Threads to my code to make it work as I've never use them and I'm totally lost.

Thanks in advance.

1条回答
一纸荒年 Trace。
2楼-- · 2019-08-08 22:01

while loop cause the UI unreponsive.

Use Widget.after instead to periodically checkfile method.

def initUI(self):
    self.popup = popup = Toplevel(self)
    Label(popup, text="Please wait until the file is created").grid(
        row=0, column=0)
    self.progressbar = progressbar = ttk.Progressbar(popup,
        orient=HORIZONTAL, length=200, mode='indeterminate')
    progressbar.grid(row=1, column=0)
    progressbar.start()
    self.checkfile()

def checkfile(self):
    if os.path.exists("myfile.txt"):
        print 'found it'
        self.progressbar.stop()
        self.popup.destroy()
    else:
        print 'not created yet'
        self.after(100, self.checkfile) # Call this method after 100 ms.

What modified:

  • Used after instead of while loop.
  • Made progressbar, popup accessible in checkfile method by making them instance attribute.
  • Moved progressbar.stop, popup.destroy to checkfile method.
查看更多
登录 后发表回答