如何在应用程序中显示函数的进度条(使用tkinter的GUI)

2024-10-04 09:21:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要显示一个进度条,向用户指示正在发生的事情。我想在单击CLASSIFY(如图所示)启动函数时显示它,然后该条将在函数结束时消失

这就是功能:

pbar = ttk.Progressbar(gui1, orient="horizontal", length=300)
pbar.place(x=500, y=120)

def Classifyall():
    pbar.start(15)

    table = BeautifulTable()
    table.column_headers = ["File Name", "File Format"]
    directory_path = '/home/.../All files/*'
    file_list = glob.glob(directory_path)
    for file in file_list:
        filepath, file_extention = os.path.splitext(file)
        filename = filepath.rsplit('/', 1)[1]
        table.append_row([filename, file_extention])
    tx.insert(END, table)
    pbar.stop()

在这里,我创建了一个包含函数的菜单栏

tool_menu = Menu(menu)
menu.add_cascade(label="Tool", menu=tool_menu)
tool_menu.add_command(label="Classify", command=Classifyall)

the image


Tags: path函数tabletoolfilenamedirectorygloblist
2条回答

您可以使用tkinter.ttk.Progressbar

import tkinter
import tkinter.ttk as ttk

w = tkinter.Tk()
pbar = ttk.Progressbar(w)

它使用两种方式实现“进步”:

1:自动前进

使用start()stop()方法,可以让进度条以一定的速度自行前进。可以向start()传递一个参数,该参数指定每次更新之间的毫秒数。因此,调用pbar.start(50)将使条形图每50毫秒前进1%。调用stop()会停止进度条并将其进度重置为0%

注意:一旦进度条完成,您必须调用stop(),否则它将重置为0%,并重新开始进度

2:手动推进

还可以通过调用step()方法手动推进进度条。必须向step()传递一个参数,该参数指定要进行的百分比。因此,调用pbar.step(35)会使进度条的进度增加35%。是的,负数也是允许的:pbar.step(-35)

最好在线程中运行耗时的任务,否则会使tkinter应用程序不响应

我使用另一个函数start_classification(),在选择菜单项Classify后执行

在该职能范围内:

  • 不确定模式下创建进度条
  • 启动进度条动画
  • 创建一个tkinter变量来保存来自Classifyall()的结果
  • 启动子线程以执行Classifyall()
  • 等待子线程完成
  • 销毁进度条
  • 使用来自Classifyall()的结果更新文本框
import threading
from tkinter import ttk
...

# added argument var (a tkinter StringVar)
def Classifyall(var):
    table = BeautifulTable()
    table.column_headers = ["File Name", "File Format"]
    directory_path = '/home/.../All files/*'
    file_list = glob.glob(directory_path)
    for file in file_list:
        filepath, file_extention = os.path.splitext(file)
        filename = filepath.rsplit('/', 1)[1]
        table.append_row([filename, file_extention])

    # note that it is not safe to update tkinter widget in a child thread
    # so use the passed tkinter variable to save the result instead
    var.set(table)

def start_classification():
    # create a progress bar and start the animation
    pbar = ttk.Progressbar(gui1, orient='horizontal', length=300, mode='indeterminate')
    pbar.place(relx=0.5, rely=0.5, anchor='c')
    pbar.start()

    var = StringVar() # hold the result from Classifyall()
    # execute Classifyall() in a child thread
    threading.Thread(target=Classifyall, args=(var,)).start()
    # wait for the child thread to complete
    tx.wait_variable(var)

    pbar.destroy()
    tx.insert(END, var.get())

...

tool_menu = Menu(menu)
tool_menu.add_command(label='Classify', command=start_classification) # call start_classification() instead
menu.add_cascade(label='Tool', menu=tool_menu)

...

相关问题 更多 >