Progressbar with Percentage Label?
This is possible using a ttk.Style
. The idea is to modify the layout of the Horizontal.TProgressbar
style (do the same with Vertical.TProgressbar
for a vertical progressbar) to add a label inside the bar:
Usual Horizontal.TProgressbar
layout:
[('Horizontal.Progressbar.trough', {'children': [('Horizontal.Progressbar.pbar', {'side': 'left', 'sticky': 'ns'})], 'sticky': 'nswe'})]
With an additional label:
[('Horizontal.Progressbar.trough', {'children': [('Horizontal.Progressbar.pbar', {'side': 'left', 'sticky': 'ns'})], 'sticky': 'nswe'}), ('Horizontal.Progressbar.label', {'sticky': 'nswe'})]
Then, the text of the label can be changed with style.configure
.
Here is the code:
import tkinter as tkfrom tkinter import ttkroot = tk.Tk()style = ttk.Style(root)# add label in the layoutstyle.layout('text.Horizontal.TProgressbar', [('Horizontal.Progressbar.trough', {'children': [('Horizontal.Progressbar.pbar', {'side': 'left', 'sticky': 'ns'})], 'sticky': 'nswe'}), ('Horizontal.Progressbar.label', {'sticky': ''})])# set initial textstyle.configure('text.Horizontal.TProgressbar', text='0 %')# create progressbarvariable = tk.DoubleVar(root)pbar = ttk.Progressbar(root, style='text.Horizontal.TProgressbar', variable=variable)pbar.pack()def increment(): pbar.step() # increment progressbar style.configure('text.Horizontal.TProgressbar', text='{:g} %'.format(variable.get())) # update label root.after(200, increment)increment()root.mainloop()