如何让Tkinter进度条达最大值后自动停止并执行后续操作
Fixing Tkinter Progressbar Auto-Stop and Post-Completion Action
Let's walk through the issues in your current code and fix them to get your progressbar working exactly as you want:
Key Problems in Your Existing Code
- You're incorrectly using
self.after(100, self.textFileCreation())— the parentheses mean you're running the function immediately instead of passing it as a callback toafter(). - The
self.processvariable isn't initialized, so it might start from an unexpected value when you launch the progressbar. - The progress update loop doesn't cleanly stop once the maximum value is hit.
Step 1: Initialize Progress Variables
Add this to your class's __init__ method to ensure we always start from 0:
def __init__(self, master): # ... your existing initialization code ... self.process = 0 # Initialize progress counter to 0 self.progressbar = ttk.Progressbar(self, orient="horizontal", length=300, maximum=100, mode="determinate") self.progressbar.place(x=250, y=225)
Step 2: Fix the Progress Update Function
Here's the corrected textFileCreation function with proper auto-stop and post-completion logic:
def textFileCreation(self): # Update progress value self.process += 10 self.progressbar['value'] = self.process if self.progressbar['value'] >= self.progressbar['maximum']: # Progress complete: run your post-completion actions msg_success = f"The file {self.dataName}.ctm has been created in the folder: {self.dataDirectory}" messagebox.showinfo("success", msg_success) create_file(self.dataPath, self.dataName, self.dataDirectory) # Reset progress for future launches self.process = 0 return else: # Schedule next progress update (no parentheses after the function name!) self.after(100, self.textFileCreation)
Step 3: Reset Progress Before Launching
In your launchCallBack function's else block, add lines to reset the progressbar so each launch starts fresh:
else : # Reset progress counter and bar before starting self.process = 0 self.progressbar['value'] = 0 self.textFileCreation()
What This Fixes
- The progressbar now increments smoothly every 100ms until it reaches 100.
- Once it hits the maximum, it automatically stops updating, shows the success message, and runs your
create_filefunction. - Every time you click the launch button, the progress starts from 0 instead of picking up where it left off.
内容的提问来源于stack exchange,提问作者Lucas




