首页 > 解决方案 > Create tkinter progress widget at the start of function and destroy at end of function

问题描述

I have a somewhat long bit of code that I've tried to simplify here to ask my question. There are actually many lines after the readfile in my real code, to process that data and it can be quite lengthy depending on the size of the file read.

Func1 is triggered by pressing Bt1.

I want the steps of Func1 to execute in the following specific order

  1. Bt1 to be destroyed
  2. progress (my progress bar) to appear on screen
  3. The file to be read.

How would I best edit this code below to do this.

I'm not worried that the progress bar doesn't mean anything specific. I'm fine it just displaying to notify something is being processed.

root=Tk()
root.title('text')
root.configure(background="ghost white")

def func1:
        Bt1.destroy()
        progress = ttk.Progressbar(root, orient = HORIZONTAL, mode = 'indeterminate')
        readfile = pd.read_csv('file.csv')
       
      
Bt1 = Button(root, command = func1)
Bt1.grid()


root.mainloop()

标签: pythontkinter

解决方案


您可以将冗长的任务放在一个线程中,并在任务完成时使用StringVarandwait_variable()通知主线程。

下面是修改后的代码:

import threading

...

def lengthy_func(var):
    readfile = pd.read_csv('file.csv')
    # other lengthy tasks
    # ...

    # task completed, notify main thread
    var.set('')

def func1():
    Bt1.destroy()
    progress = ttk.Progressbar(root, orient=HORIZONTAL, mode='indeterminate')
    progress.grid()
    var = StringVar()
    threading.Thread(target=lengthy_func, args=(var,), daemon=True).start()
    progress.start(10) # start the progress bar animation
    root.wait_variable(var) # wait for the lengthy task to complete
    progress.destroy()

推荐阅读