【发布时间】:2021-08-08 23:34:24
【问题描述】:
我在 tkinter 脚本中有一个 Toplevel 窗口,其中包含两个对应于嵌套循环的进度条。我想在 Toplevel 窗口中添加一个停止按钮来终止执行并关闭 Toplevel 窗口而不是根。
from tkinter import Tk, Toplevel,Button,Label,TOP,BOTH,DoubleVar
from tkinter.ttk import Progressbar
import time
root = Tk()
root.configure(bg='lightgray')
root.wm_title("Main")
progress_window = Toplevel()
progress_window.attributes('-topmost', 'true')
progress_window.configure(bg='lightgrey')
progress_window.wm_title("Progress")
progress_window_label = Label(root, text="")
progress_window.geometry('600x300')
progress_window_label.pack()
M=4 # outer loop
N=5 # inner loop
progress1_var=DoubleVar()
progress1bar=Progressbar(master=progress_window,variable=progress1_var,length=M)
progress1bar.pack(side=TOP,ipady=5,fill=BOTH,expand=True)
progress1_var.set(0)
progress1bar.update()
progress1bar_label=Label(master=progress_window,text='Bar1',bg='lightgray')
progress1bar_label.pack(side=TOP,pady=5,fill=BOTH, expand=True)
progress2_var = DoubleVar()
progress2bar=Progressbar(master=progress_window,variable=progress2_var,length=N)
progress2bar.pack(side=TOP,ipady=5,fill=BOTH, expand=True)
progress2_var.set(0)
progress2bar.update()
progress2bar_label=Label(master=progress_window,text='Bar2',bg='lightgray')
progress2bar_label.pack(side=TOP,pady=5,fill=BOTH, expand=True)
def _stop():
return
stop_button=Button(master=progress_window, text="Cancel",command=_stop)
stop_button.pack(side=TOP,pady=5,fill=BOTH, expand=True)
for t in range(M):
progress1_var.set(t/M)
progress1bar_label.config(text='Bar 1: '+str(round((t+1)/M*100,3))+'%')
progress1bar.update()
progress2_var.set(0)
progress2bar.update()
for i in range(N):
progress2_var.set(i/N)
time.sleep(1.0) #Sleep to slow down execution and view progress window
progress2bar_label.config(text='Bar 2: '+str(round((i+1)/N*100,3))+'%')
progress2bar.update()
progress_window.destroy()
root.mainloop()
停止按钮出现在应该但不起作用的位置并停止执行。这一定是一个非常根本的错误,但我不知道如何纠正它。
【问题讨论】:
-
我希望你知道调用
_stop()绝对不会做任何事情(除了浪费极少量的资源),我建议在那些循环中增加一些标志并使用一些 if 语句会破坏它们