Progressbar with Percentage Label?

前端 未结 1 1324
时光取名叫无心
时光取名叫无心 2020-12-18 13:45

How can I put a label in the middle of a progressbar that shows the percentage? The problem is that python doesn\'t support transparency for label backgrounds, so I don\'t k

相关标签:
1条回答
  • 2020-12-18 14:24

    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 tk
    from tkinter import ttk
    
    root = tk.Tk()
    
    style = ttk.Style(root)
    # add label in the layout
    style.layout('text.Horizontal.TProgressbar', 
                 [('Horizontal.Progressbar.trough',
                   {'children': [('Horizontal.Progressbar.pbar',
                                  {'side': 'left', 'sticky': 'ns'})],
                    'sticky': 'nswe'}), 
                  ('Horizontal.Progressbar.label', {'sticky': ''})])
    # set initial text
    style.configure('text.Horizontal.TProgressbar', text='0 %')
    # create progressbar
    variable = 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()
    

    0 讨论(0)
提交回复
热议问题