python - 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
- Bt1 to be destroyed
- progress (my progress bar) to appear on screen
- 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()
解决方案
您可以将冗长的任务放在一个线程中,并在任务完成时使用StringVar
andwait_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()
推荐阅读
- python - 如何在 Python 中使用扩展运算符
- ios - rx.sentMessage(#selector(UIViewController.viewDidLoad)) 没有触发
- rxjs - 添加到先前合并的 Observable
- android - 如何修复“android.arch.lifecycle:runtime”在 Flutter 中的编译时和运行时版本不同?
- wpf - WPF 弹出控件正在立即关闭
- regex - 如何使用 REGEX 检查字符串是否仅以特定值结尾
- html - How to control position overlap on other elements?
- javascript - 通过 Discord OAuth 传递字符串?
- c# - 即使条件保持为真,如何只运行一次进程
- perl - 在 Perl foreach 循环中分配两个变量