首页 > 解决方案 > Tkinter Progressbar 应用程序被另一个应用程序调用和更新

问题描述

我正在尝试实现一个包含一个进度条小部件的弹出窗口。弹出窗口必须由绑定到属于主应用程序的按钮的函数调用、更新和终止。我尝试使用线程模块,但有些东西不能正常工作,因为当弹出窗口(包含进度条的窗口)被杀死时主应用程序阻塞[quit()方法]。似乎一些未决和/或循环过程保持活动状态并阻止一切。有人可以帮帮我吗?这是代码:

from tkinter import *
from tkinter import ttk
import threading
from time import sleep


class ProgressbarApp(threading.Thread):
    def __init__(self, text_string: str, max_value: int):
        self.max_value = max_value
        self.text_string = text_string
        threading.Thread.__init__(self)
        self.start()

    def run(self):
        self.root = Tk()
        root_width = 500
        root_height = 100
        root_x = max(0 , round((self.root.winfo_screenwidth() - root_width) / 2))
        root_y = max(0 , round((self.root.winfo_screenheight() - root_height) / 2) - 10)
        self.root.geometry(str(root_width) + "x" + str(root_height) + "+" + str(root_x) + "+" + str(root_y))
        self.root.resizable(False, False)
        # self.root.protocol("WM_DELETE_WINDOW", self.quit)

        Label(self.root, text = self.text_string).grid(row = 0, column = 0)
        self.pb = ttk.Progressbar(self.root, orient = 'horizontal', length = 400, mode = 'determinate', value = 0, maximum = self.max_value)
        self.pb.grid(row = 1, column = 0, padx = 50, pady = 20)
        
        self.root.mainloop()

    def update(self, value: int):
        self.pb['value'] = value
        
    def quit(self):
        pass


class Main_App():
    def __init__(self):
        self.master = Tk()
        master_width = 500
        master_height = 200
        master_x = max(0 , round((self.master.winfo_screenwidth() - master_width) / 2))
        master_y = max(0 , round((self.master.winfo_screenheight() - master_height) / 2) - 10)
        self.master.geometry(str(master_width) + "x" + str(master_height) + "+" + str(master_x) + "+" + str(master_y))
        self.master.resizable(False, False)
        
        self.button1 = Button(self.master, text = "Load", command = lambda: self.My_Fcn(2)).pack()
    
        self.master.mainloop()


    def My_Fcn(self, max_value: int):
        my_pb = ProgressbarApp("Loading data...", max_value)
        for i in range(max_value):
            sleep(1)
            my_pb.update(i+1)
        my_pb.root.quit()


app = Main_App()

标签: pythontkinterpython-multithreading

解决方案


推荐阅读