【问题标题】:Button callback only works one time due to threading由于线程,按钮回调只能工作一次
【发布时间】:2020-10-18 04:12:19
【问题描述】:

由于我如何设置“command=”参数,我只能使用此按钮的回调一次。我希望能够在它完成后再次运行这个回调函数,但是我不知道如何给'command ='参数一个新的线程对象。我按下它一次并完成函数的过程,但是一旦我在完成后再次按下按钮,我就会得到'RuntimeError:线程只能启动一次。这是按钮和回调的代码:

def ocr_callback():
    no_file_to_save_to = False
    try:
        status_label.pack_forget()
        for f in files:    # files comes from another callback and is globally defined
            name, extension = os.path.splitext(f)
            if extension != '.pdf':
                raise
        if len(files) == 1:
            new_file = filedialog.asksaveasfilename(filetypes=[('PDF', '.pdf')], defaultextension='.pdf')
            if not new_file:
                no_file_to_save_to = True
                raise
            try:
                ocrmypdf.ocr(files[0], new_file, use_threads=True)
            except ocrmypdf.exceptions.PriorOcrFoundError:
                ocrmypdf.ocr(files[0], new_file, redo_ocr=True, use_threads=True)
        elif len(files) > 1:
            directory = filedialog.askdirectory()
            if not directory:
                no_file_to_save_to = True
                raise
            for f in files:
                file_name = f.split('/')[-1]
                try:
                    ocrmypdf.ocr(f, directory + '/' + file_name, use_threads=True)
                except ocrmypdf.exceptions.PriorOcrFoundError:
                    ocrmypdf.ocr(f, directory + '/' + file_name, redo_ocr=True, use_threads=True)
        status_label.config(text='Process Complete!', fg='blue')
        status_label.pack(expand='yes')
    except:
        if no_file_to_save_to:
            status_label.config(text='No file to save to. Process Cancelled', fg='blue')
        else:
            status_label.config(text='Error: One or more of the files could be corrupt.', fg='red')
        status_label.pack(expand='yes')


ocr_button = Button(root, text='OCR Files', relief='groove', bg='#5D1725', bd=0, width=scaled(20), fg='white',
                    command=threading.Thread(target=ocr_callback).start, state=DISABLED)
ocr_button.pack()

有什么想法可以改变它以使其工作吗?我知道这个函数必须是线程化的,否则窗口将停止并自行冻结,直到它完成。 'ocr' 函数是导致线程阻塞和必要性的原因。

【问题讨论】:

    标签: python-3.x multithreading tkinter python-multithreading


    【解决方案1】:

    您可能应该从启动函数启动线程,而不是从按钮命令内部。

    可能是这样的:

    def launch_cmd(dummy=None):
        threading.Thread(target=ocr_callback).start()
    
    ...
    ocr_button = Button(root, text='OCR Files', relief='groove', bg='#5D1725',\
                        bd=0, width=scaled(20), fg='white', command=launch_cmd, state=DISABLED)
    

    【讨论】:

    • 这成功了!谢谢你。另外,'dummy' 参数有什么作用?
    • 好,好 - dummy 是一个占位符,以防你的回调发送一个我们不使用的 arg,默认情况下。您可以安全地删除它。
    猜你喜欢
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    • 2022-07-09
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    相关资源
    最近更新 更多