Search code examples
pythonlinuxwindowstkinterprogress-bar

Tkinter progress bar works on Linux but not on Windows


I wrote the following basic code sample that creates a main window with a button. When the button is pressed a second window with a progress bar should appear and stay open until the progress is complete. This works fine on Linux but on Windows the second window appears blank with no progress bar. Given that this will be part of an application that runs on Windows. What should I do? Is this a bug or what's going on?

I'm using python 3.12.5 on both Linux and Windows 11 (build 22631).

The code

import tkinter.ttk as ttk
import tkinter as tk
import time


def cpw():
    tasks = 5
    increment = 100 / tasks

    pw = tk.Toplevel()
    pw.title("Progress Window")
    pw.geometry("300x135")
    pb = ttk.Progressbar(
        pw,
        name="pb",
        orient=tk.HORIZONTAL,
        length=200,
        mode="determinate",
    )
    pb.pack()

    i = 0
    while i < tasks:
        i += 1
        pb["value"] += increment
        pb.update_idletasks()
        time.sleep(1)

    pw.destroy()


root = tk.Tk()
root.title("Example")
root.geometry("150x100")

tk.Button(root, text="Process", command=cpw).pack()

root.mainloop()

Solution

  • Thanks to @acw1668 who pointed out in the comments that .update_idletasks() may not handle pending creation of widgets. Adding pb.update() or also pb.wait_visibility(pw) before pb.pack() will ensure the creation and visibility of the progress window and bar.

    Documentation here