如何使tkinter的窗口在单击窗口时不显示"not responding"



当我的代码在tkinter的窗口中点击run按钮后运行时,它会显示"没有响应";当我点击它的时候。如何使其在单击时不响应并显示加载进度?这是加载我使用的代码。

from tkinter import *
from tkinter.ttk import *
import time
window = Tk()
window.geometry("400x200")
percent = StringVar()
text = StringVar()
def start():
def task():
bar['value']=0
GB = 100
download = 0
speed = 1
while(download<GB):
time.sleep(0.05)
bar['value']+=(speed/GB)*100
download+=speed
percent.set(str(int((download/GB)*100))+"%")
text.set(str(download)+"/"+str(GB)+" GB completed")
window.after(2000, None)
window.update_idletasks()
window.after(1, task)
window.after(100, task)
bar = Progressbar(window,orient=HORIZONTAL,length=300)
bar.pack(pady=10)
percentLabel = Label(window,textvariable=percent).pack()
taskLabel = Label(window,textvariable=text).pack()
button = Button(window,text="download",command=start).pack()
window.mainloop()    

我从start中提取了函数task,并实现了Buttondisable,以防止多次按下按钮。

还对2.x和3.x版本的进行了更新百分比和下载输出代码

try:
import tkinter as tk
from tkinter import ttk
except ImportError:
# Can't test it but according to this: https://stackoverflow.com/a/23984633/11106801
import Tkinter as tk
import ttk
window = tk.Tk()
window.geometry("400x200")
percent = tk.StringVar(master=window)
text = tk.StringVar(master=window)
def task(download):
bar['value'] = download
GB = 100
speed = 1
if GB >= download:
bar['value'] += speed/GB*100
percent.set("{} %".format(int(download/GB*100)))
text.set("{} / {}  GB completed".format(download, GB))
window.after(100, task, download+1)
def start():
button.config(state="disabled")
task(0)
bar = ttk.Progressbar(window, orient="horizontal", length=300)
bar.pack(pady=10)
percentLabel = tk.Label(window, textvariable=percent)
percentLabel.pack()
taskLabel = tk.Label(window, textvariable=text)
taskLabel.pack()
button = tk.Button(window, text="download", command=start)
button.pack()
window.mainloop()

试试这个:

import tkinter as tk
from tkinter import ttk
window = tk.Tk()
window.geometry("400x200")
percent = tk.StringVar(master=window)
text = tk.StringVar(master=window)
def start():
download = 0
def task(download):
bar["value"] = download
GB = 100
speed = 1
if download <= GB:
bar["value"] += (speed/GB)*100
percent.set(str(int((download/GB)*100))+"%")
text.set(str(download)+"/"+str(GB)+" GB completed")
window.after(1000, task, download+1)
window.after(1000, task, 0)
bar = ttk.Progressbar(window,orient="horizontal", length=300)
bar.pack(pady=10)
percentLabel = tk.Label(window, textvariable=percent)
percentLabel.pack()
taskLabel = tk.Label(window, textvariable=text)
taskLabel.pack()
button = tk.Button(window, text="download", command=start)
button.pack()
window.mainloop()  

最新更新