我有一个应用程序,我想在计算期间显示一个进度条。因此,我的应用程序上有一个按钮来运行一个函数并显示进度条,但是子窗口只出现在计算的末尾。
要再现此代码,您可以尝试下面的代码:
import tkinter as tk
from tkinter import ttk as ttk
class MainApplication:
def __init__(self, master):
self.master = master
self.button_start = tk.Button(
self.master, text='Begin', command=self.upload_button)
self.button_start.place(relx=0.5, rely=0.5)
def upload_button(self):
newWindow = tk.Toplevel(self.master)
newWindow.title("Chargment...")
newWindow.geometry("400x70")
# A Label widget to show in toplevel
ttk.Label(newWindow, text="Please wait...").pack()
pb = ttk.Progressbar(newWindow, length=300)
pb.pack()
pb.start(10)
for i in range(90000):
print(i)
window = tk.Tk()
window.title("my title")
MainApplication(window)
window.mainloop()编辑
我试图使用线程和事后解决我的问题,但我被卡住了。我不知道如何用熊猫代替蟒蛇的后置方法。我不能仅仅将延迟的一个值放在后置方法中,因为如果最终用户工作在一个小表或更大的表上,延迟可能是不同的。
import tkinter as tk
from PIL import Image, ImageTk
import threading
import time
from tkinter import messagebox
from itertools import count
class GIFLabel(tk.Label):
"""a label that displays images, and plays them if they are gifs"""
def load(self, im):
if isinstance(im, str):
im = Image.open(im)
self.loc = 0
self.frames = []
try:
for i in count(1):
self.frames.append(ImageTk.PhotoImage(im.copy().resize((20,20))))
im.seek(i)
except EOFError:
pass
try:
self.delay = im.info['duration']
except:
self.delay = 100
if len(self.frames) == 1:
self.config(image=self.frames[0])
else:
self.next_frame()
def unload(self):
self.config(image="")
self.frames = None
def next_frame(self):
if self.frames:
self.loc += 1
self.loc %= len(self.frames)
self.config(image=self.frames[self.loc])
self.after(self.delay, self.next_frame)
class MainApplication:
def __init__(self, master):
self.master = master
self.button_start = tk.Button(self.master, text='Begin', command=self.upload_button)
self.button_start.place(relx=0.5, rely=0.5)
self.loading = GIFLabel(self.master)
self.loading.place(relx=0.5, rely=0.7)
self.loading.load('loading.gif')
def wait_generate(self):
if self.update_Thread.isAlive():
self.master.after(500, self.wait_generate)
else:
self.loading.unload()
self.loading.load('ok.png')
messagebox.showinfo("Complete", "Report generation completed!")
def upload_button(self):
self.update_Thread = threading.Thread(target=time.sleep, args=(5,))
self.update_Thread.start()
self.wait_generate()
window = tk.Tk()
window.title("my title")
MainApplication(window)
window.mainloop()发布于 2020-07-27 11:33:53
当您在for循环中运行时,tkinter窗口没有机会自动更新(通常是通过mainloop)。
有两种选择
though)
for循环中的窗口
您可以研究如何使用线程,但这里最简单的选项是在for循环中包含以下任一项:
self.master.update()或newWindow.update()
这将手动更新窗口,这意味着进度条可以更新并变得可见。
它应该是这样的:
for i in range(90000):
print(i)
# you can use
self.master.update()
# or
newWindow.update()https://stackoverflow.com/questions/63113382
复制相似问题