【问题标题】:progressbar in Tkinter with a label insideTkinter 中的进度条,里面有标签
【发布时间】:2014-09-06 05:34:27
【问题描述】:

是否可以改进我在 Tkinter-Python 中的进度条在中间添加标签(例如:读取文件)?

我试图找到一个优雅的编码解决方案,但没有真正的结果

from Tkinter import *
import ttk
import tkFileDialog
import time

class MainWindow(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("ProgressBar example")
        self.master.minsize(200, 100)
        self.grid(sticky=E+W+N+S)

        top = self.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)

        self.start_ind = Button(self, text='Start indeterminate', command=self.start_ind, activeforeground="red")
        self.start_ind.grid(row=0, column=0, pady=2, padx=2, sticky=E+W+N+S)

        self.pbar_ind = ttk.Progressbar(self, orient="horizontal", length=300, mode="indeterminate")
        self.pbar_ind.grid(row=1, column=0, pady=2, padx=2, sticky=E+W+N+S)

   def start_ind(self):
        for i in xrange(50):
            self.pbar_ind.step(1)
            self.update()
            # Busy-wait
            time.sleep(0.1)

if __name__=="__main__":
   d = MainWindow()
   d.mainloop()

【问题讨论】:

  • 文档没有提到在进度条小部件中嵌入标签,这通常意味着它不受支持。您将不得不考虑编写自定义小部件。

标签: python tkinter progress-bar


【解决方案1】:

您是否尝试过创建一个文本标签并将其放在同一行/列中并将其设置为相同大小,如下所示:

self.Lab = Label(self,length=200)
self.Lab.grid(row=1,column=0,pady=2,padx=2,sticky=E+W+N+S))

但你会想把它放在进度条小部件之后。

【讨论】:

  • 这不起作用。它只是覆盖了进度条,标签不能有透明背景。
【解决方案2】:

我通过创建自定义 ttk 样式布局在进度条内添加了标签。通过配置样式改变标签的文字:

from tkinter import Tk
from tkinter.ttk import Progressbar, Style, Button
from time import sleep


root = Tk()
s = Style(root)
# add the label to the progressbar style
s.layout("LabeledProgressbar",
         [('LabeledProgressbar.trough',
           {'children': [('LabeledProgressbar.pbar',
                          {'side': 'left', 'sticky': 'ns'}),
                         ("LabeledProgressbar.label",   # label inside the bar
                          {"sticky": ""})],
           'sticky': 'nswe'})])

p = Progressbar(root, orient="horizontal", length=300,
                style="LabeledProgressbar")
p.pack()

# change the text of the progressbar, 
# the trailing spaces are here to properly center the text
s.configure("LabeledProgressbar", text="0 %      ")

def fct():
    for i in range(1, 101):
        sleep(0.1)
        p.step()
        s.configure("LabeledProgressbar", text="{0} %      ".format(i))
        root.update()

Button(root, command=fct, text="launch").pack()

root.mainloop()

【讨论】:

  • 为什么它看起来更像是一个按钮而不是 Windows 中的进度条?
  • @YılmazAlpaslan 也许这是因为 Windows 默认主题不像其他主题那样可自定义。尝试在s = Style(root) 之后添加s.theme_use("clam")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多