带百分比标签的进度条?

时间:2017-12-19 23:50:08

标签: python tkinter label transparency

如何在显示百分比的进度条中间放置标签? 问题是python不支持标签背景的透明度,所以我不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:4)

使用ttk.Style可以做到这一点。我们的想法是修改Horizontal.TProgressbar样式的布局(对于垂直进度条对Vertical.TProgressbar执行相同的操作)以在栏中添加标签:

通常Horizontal.TProgressbar布局:

[('Horizontal.Progressbar.trough',
  {'children': [('Horizontal.Progressbar.pbar',
     {'side': 'left', 'sticky': 'ns'})],
   'sticky': 'nswe'})]

附加标签:

[('Horizontal.Progressbar.trough',
  {'children': [('Horizontal.Progressbar.pbar',
     {'side': 'left', 'sticky': 'ns'})],
   'sticky': 'nswe'}),
 ('Horizontal.Progressbar.label', {'sticky': 'nswe'})]

然后,可以使用style.configure更改标签文本。

以下是代码:

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()

screenshot of the result

相关问题