Search code examples
pythonuser-interfacetkinterprogress

Python TKinter progress bar label not acting correctly


I have really simple program with two progress bars in a window. I try only update the first progress bar, but the second progress bars label updates as well, when it shouldn't.

I am using j_4321's answer from this post on progress bar labels.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()


# Progress bar #1
style_1 = ttk.Style(root)
style_1.layout('text.Horizontal.TProgressbar',
               [('Horizontal.Progressbar.trough',
                 {'children': [('Horizontal.Progressbar.pbar',
                                {'side': 'left', 'sticky': 'ns'})],
                  'sticky': 'nswe'}),
                ('Horizontal.Progressbar.label', {'sticky': ''})])
style_1.configure('text.Horizontal.TProgressbar', text='0 %')
variable_1 = tk.DoubleVar(root)
pbar_1 = ttk.Progressbar(root, style='text.Horizontal.TProgressbar', variable=variable_1)
pbar_1.pack()


# Progress bar #2
style_2 = ttk.Style(root)
style_2.layout('text.Horizontal.TProgressbar',
               [('Horizontal.Progressbar.trough',
                 {'children': [('Horizontal.Progressbar.pbar',
                                {'side': 'left', 'sticky': 'ns'})],
                  'sticky': 'nswe'}),
                ('Horizontal.Progressbar.label', {'sticky': ''})])
style_2.configure('text.Horizontal.TProgressbar', text='0 %')
variable_2 = tk.DoubleVar(root)
pbar_2 = ttk.Progressbar(root, style='text.Horizontal.TProgressbar', variable=variable_2)
pbar_2.pack()


def increment():
    # This dosn't change pbar_2's value, as it should act.
    pbar_1.step()

    # Why does this style_1.configure also change the text from style_2 as well???
    style_1.configure('text.Horizontal.TProgressbar', text='{:g} %'.format(variable_1.get()))
    root.after(200, increment)


increment()

root.mainloop()

Solution

  • You get this weird behavior because you use the same layout. To fix this change the name of the second layout. In this case I added '1' to the name : 'text.Horizontal.TProgressbar1'

    style_2 = ttk.Style(root)
    style_2.layout('text.Horizontal.TProgressbar1',
                   [('Horizontal.Progressbar.trough',
                     {'children': [('Horizontal.Progressbar.pbar',
                                    {'side': 'left', 'sticky': 'ns'})],
                      'sticky': 'nswe'}),
                    ('Horizontal.Progressbar.label', {'sticky': ''})])
                    
    style_2.configure('text.Horizontal.TProgressbar1', text='0 %')
    variable_2 = tk.DoubleVar(root)
    
    pbar_2 = ttk.Progressbar(root, style='text.Horizontal.TProgressbar1', variable=variable_2)
    pbar_2.pack()