Step 1: Set Up Your App Window
First, import the libraries and set up your main window:
import tkinter as tk
from tkinter import ttk
import time
import threading
root = tk.Tk()
root.title("File Downloader")
root.geometry("300x150")
Step 2: Add the Progress Bar
Let’s add a horizontal progress bar with a label to show percentage:
progress = ttk.Progressbar(root, orient="horizontal", length=250, mode="determinate")
progress.pack(pady=20)
progress_label = tk.Label(root, text="Waiting to start...")
progress_label.pack()
Step 3: Simulate a Download
We simulate the progress using a loop that updates the bar and label:
def download_simulation():
for i in range(101):
progress['value'] = i
progress_label.config(text=f"Downloading... {i}%")
time.sleep(0.05)
progress_label.config(text="Download complete!")
Step 4: Use Threads to Keep the UI Responsive
Running the loop directly would freeze the UI. So, we run it in a thread:
def start_download():
threading.Thread(target=download_simulation).start()
Step 5: Add a Button to Start the Download
Hook everything up with a button:
download_button = tk.Button(root, text="Start Download", command=start_download)
download_button.pack(pady=10)
Step 6: Start the App Loop
root.mainloop()
Step 7: Complete Code
import tkinter as tk
from tkinter import ttk
import time
import threading
def start_download():
# Run the download simulation in a separate thread so the UI stays responsive
threading.Thread(target=download_simulation).start()
def download_simulation():
for i in range(101):
progress['value'] = i
progress_label.config(text=f"Downloading... {i}%")
time.sleep(0.05) # Simulate download time
progress_label.config(text="Download complete!")
# Create the main window
root = tk.Tk()
root.title("File Downloader")
root.geometry("300x150")
# Create progress bar
progress = ttk.Progressbar(root, orient="horizontal", length=250, mode="determinate")
progress.pack(pady=20)
# Label to show progress percentage
progress_label = tk.Label(root, text="Waiting to start...")
progress_label.pack()
# Download button
download_button = tk.Button(root, text="Start Download", command=start_download)
download_button.pack(pady=10)
# Run the app
root.mainloop()