如何显示“正在加载...”,然后在tkinter中单击按钮后运行脚本?

问题描述 投票:0回答:2

我想显示“正在加载...”,然后在用户等待时执行脚本。

我知道画布只能在每个循环之后进行更新,并且在调用按钮命令时画布被冻结。

我该如何解决?

当前,没有文本出现。成功文本确实出现。

import tkinter as tk
import main


root = tk.Tk()  # create GUI instance
root.title('Exam Closeout')  # name GUI

def run_script():
    '''
    Run the script from main, that is, the data script.

    :return: void
    '''
    # show loading status: currently doesn't work, need to understand queue better
    current_text = tk.StringVar()
    current_text.set('Loading...')
    tk.Label(root, textvariable=current_text).grid(row=4, column=1, sticky='w')
    subject = entry_1.get() # grab subject from user input
    try:
        # call main
        main.test(subject)
        # show finish status
        current_text.set('Script successfully finished. You may exit out of this window now')
    except Exception as e:   # catch exceptions. currently doesn't show specific exception
        current_text.set("Error occurred. Try looking at documentation")


# label with instructions
tk.Label(root, text="Thank you for using me...").grid(row=1, column=1, sticky='w')

# label to show users where to enter exam
tk.Label(root, text="Enter exam code:").grid(row=2, column=1, sticky='w')

# blank box to enter exam into
entry_1 = tk.Entry(root,width=40)   # entry has to be its own line - for more, see below
entry_1.grid(row=2, column=2, columnspan=2)

# button to run script
tk.Button(root,text="Run", command=run_script).grid(row=3, column=3)

# start canvas
root.mainloop()

main.py

import time

def test(exam):
    time.sleep(5)
    print(exam)

如果很重要,主要方法实际上是一个数据分析脚本,它接收数据框,对其进行操作并导出Excel数据集。

python tkinter
2个回答
0
投票

在下面指示的位置添加对通用update_idletasks()小部件方法的调用:

update_idletasks()

0
投票

您可以为脚本启动一个新线程,但是当用户在运行程序时退出该程序时,您必须处理这种情况,但是这个想法是:

def run_script():
    '''
    Run the script from main, that is, the data script.

    :return: void
    '''
    # show loading status: currently doesn't work, need to understand queue better
    current_text = tk.StringVar()
    current_text.set('Loading...')
    tk.Label(root, textvariable=current_text).grid(row=4, column=1, sticky='w')
    subject = entry_1.get() # grab subject from user input
    try:
        root.update_idletasks()  #### ADD THIS LINE.
        # call main
        main.test(subject)
        # show finish status
        current_text.set('Script successfully finished. You may exit out of this window now')
    except Exception as e:   # catch exceptions. currently doesn't show specific exception
        current_text.set("Error occurred. Try looking at documentation")
© www.soinside.com 2019 - 2024. All rights reserved.