带有百分比标签的进度条? [英] Progressbar with Percentage Label?
问题描述
如何在显示百分比的进度条中间放置标签?问题是python不支持标签背景的透明度,所以我不知道如何解决.
这可以使用 ttk.Style
实现.想法是修改 Horizontal.TProgressbar
样式的布局(对垂直进度条执行与 Vertical.TProgressbar
相同的操作)以在条内添加标签:>
通常的 Horizontal.TProgressbar
布局:
[('Horizontal.Progressbar.trough',{'children': [('Horizontal.Progressbar.pbar',{'side': 'left', 'sticky': 'ns'})],'粘性':'nswe'})]
带有附加标签:
[('Horizontal.Progressbar.trough',{'children': [('Horizontal.Progressbar.pbar',{'side': 'left', 'sticky': 'ns'})],'粘性':'nswe'}),('Horizontal.Progressbar.label', {'sticky': 'nswe'})]
然后,可以使用style.configure
更改标签的文本.
代码如下:
将 tkinter 导入为 tk从 tkinter 导入 ttk根 = tk.Tk()风格 = ttk.Style(root)# 在布局中添加标签style.layout('text.Horizontal.TProgressbar',[('Horizontal.Progressbar.trough',{'children': [('Horizontal.Progressbar.pbar',{'side': 'left', 'sticky': 'ns'})],'粘性':'nswe'}),('Horizontal.Progressbar.label', {'sticky': ''})])# 设置初始文本style.configure('text.Horizontal.TProgressbar', text='0 %')# 创建进度条变量 = tk.DoubleVar(root)pbar = ttk.Progressbar(root, style='text.Horizontal.TProgressbar', variable=variable)pbar.pack()定义增量():pbar.step() # 增加进度条style.configure('text.Horizontal.TProgressbar',text='{:g} %'.format(variable.get())) # 更新标签root.after(200, 增量)增量()root.mainloop()
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 know how I can solve that.
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()
这篇关于带有百分比标签的进度条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!