如何在显示百分比的进度条中间放置一个标签? 问题是 python 不支持标签背景的透明度,所以我不知道该如何解决。
请您参考如下方法:
这可以使用 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': 'nswe'})])
# set initial text
style.configure('text.Horizontal.TProgressbar', text='0 %', anchor='center')
# 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()
样式
可以使用 style.configure 更改标签的字体、颜色和位置。例如,
style.configure('text.Horizontal.TProgressbar', foreground="red",
font='Arial 20', anchor='w')
多个进度条
文本是通过样式设置的,因此有多个带有不同标签的进度条,需要为每个使用不同的样式。但是,不需要为每个样式设置布局:像上面的代码一样创建布局 'text.Horizontal.TProgressbar',然后使用子样式 'pb1.text.Horizontal。 TProgressbar', 'pb2.text.Horizontal.TProgressbar', ... 每个进度条。然后可以更改单个进度条的文本
style.configure('pb1.text.Horizontal.TProgressbar', text=...)
