progressbar in Tkinter with a label inside

2019-09-16 12:25发布

Is It possible to improve my progressbar in Tkinter-Python adding a label in the middle (ex: reading file)?

I tried to find a elegant coding solution but without a real result

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

2条回答
该账号已被封号
2楼-- · 2019-09-16 12:38

I added the label inside the progressbar by creating a custom ttk style layout. The text of the label is changed by configuring the style:

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",
                          {"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()
查看更多
放荡不羁爱自由
3楼-- · 2019-09-16 12:49

Have you tried creating a text Label and putting it in the same row/column and setting it the same size like so:

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

But you would want to put it after the progress bar widget.

查看更多
登录 后发表回答