如何使用tkinter在两个不同的进度条中显示文本?

2024-06-28 14:52:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含两个不同的Progressbar的窗口。我想在它们上面添加不同的文本信息(即第一个是“88/1524”,第二个是“88/10000”)。 在这个问题上,我找到了一个解决方案:Displaying percentage in ttk progressbar

但是,它使用样式修改解决方案在进度条上添加文本,据我所知,所有进度条都共享样式属性text.Horizontal.TProgressbar。这意味着我不能在每个进度条上有不同的文本。当我需要更新文本时,我不知道如何针对一个特定的进度条

有没有别的办法,或者我遗漏了什么? 我是否可以实例化标签,使其具有类似text.Horizontal.TProgressbar1text.Horizontal.TProgressbar2的内容

以下是我当前没有标签的设置: Progressbars

我的困境是: enter image description here

我的部分代码:

style = tkinter.ttk.Style(root)

style.layout('text.Horizontal.TProgressbar', 
            [('Horizontal.Progressbar.trough',
            {'children': [('Horizontal.Progressbar.pbar',
                            {'side': 'left', 'sticky': 'ns'})],
                'sticky': 'nswe'}), 
            ('Horizontal.Progressbar.label', {'sticky': ''})])
style.configure('text.Horizontal.TProgressbar', text='0/0')

ProgressBarOfDirectory = tkinter.ttk.Progressbar(ProgressbarFrame,
                                                 style='text.Horizontal.TProgressbar',
                                                 orient="horizontal",
                                                 length=WidthOfElements,
                                                 mode="determinate",
                                                 maximum=NbStepOfProgressBar,
                                                 variable=PourcentageOfDirectoryAnalysisDone)
ProgressBarOfDirectory.pack(side="top")

ProgressBarOfAll = tkinter.ttk.Progressbar(ProgressbarFrame,
                                           style='text.Horizontal.TProgressbar',
                                           orient="horizontal",
                                           length=WidthOfElements,
                                           mode="determinate",
                                           maximum=NbStepOfProgressBar,
                                           variable=PourcentageOfAllAnalysisDone)


Tags: 进度条text文本styletkinter样式标签解决方案
2条回答

除非为多个小部件指定了相同的小部件样式(或者由于未指定其他内容而将相同的默认样式分配给多个小部件),否则不会共享小部件样式

为了利用这一点,这里有一个更新版本的代码,用于我的answer到另一个问题。为了确保每个Progressbar实例的独立性,它从内置的ttk.Progressbar派生一个新类,该类为创建的每个实例创建一个单独的样式对象

下面是代码以及最后的可运行演示

import tkinter as tk
import tkinter.ttk as ttk

class MyProgressBar(ttk.Progressbar):
    _inst_count = 0  # Number of class instances created.

    def __init__(self, *args, **kwargs):
        classname = type(self).__name__
        assert 'style' not in kwargs, \
               f'{classname} initializer does not support providing a ttk "style".'
        type(self)._inst_count += 1  # Increment class attribute.
        # Create a style with a different name for each instance.
        self.style = ttk.Style(root)
        self.stylename = f'text.Horizontal.TProgressbar{self._inst_count}'
        self.style.layout(self.stylename,
                          [('Horizontal.Progressbar.trough',
                            {'children': [('Horizontal.Progressbar.pbar',
                                           {'side': 'left', 'sticky': 'ns'})],
                             'sticky': 'nswe'}),
                           ('Horizontal.Progressbar.label', {'sticky': ''})])
        maximum = kwargs['maximum']
        self.style.configure(self.stylename, text=f'0/{maximum}')
        kwargs.update(style=self.stylename)
        super().__init__(*args, **kwargs)


if __name__ == '__main__':

    DELAY1 = 100
    DELAY2 = 25
    MAX1 = 1524
    MAX2 = 10000

    def progress_bar_func(delay, progress_bar):
        # Start periodic progress-bar update process.
        maximum = progress_bar.cget('maximum')
        style = progress_bar.style  # Progressbar must have a style attribute.
        root.after(delay, update_progress_bar, delay, style, progress_bar, 1, maximum)

    def update_progress_bar(delay, style, progress_bar, num, maximum):
        if num <= maximum:
            progress_bar.config(value=num)
            style.configure(progress_bar.stylename, text=f'{num}/{maximum}')
            num += 1
            root.after(delay, update_progress_bar, delay, style, progress_bar, num, maximum)

    root = tk.Tk()
    root.geometry("300x300")

    progress_bar1 = MyProgressBar(root, length=200, maximum=MAX1, value=0)
    progress_bar1.pack()
    progress_bar2 = MyProgressBar(root, length=200, maximum=MAX2, value=0)
    progress_bar2.pack()

    def start_progress_bars():
        progress_bar_func(DELAY1, progress_bar1)
        progress_bar_func(DELAY2, progress_bar2)

    progress_button = tk.Button(root, text="Start", command=start_progress_bars)
    progress_button.pack()

    root.mainloop()

下面是它运行的几个屏幕截图:

screenshots of it running

进度条本身没有显示文本的功能

您可以做的是使用标签小部件。你所要做的就是在你想要实现文本的地方放置一个标签小部件

现在您可以配置标签的文本值&;可以在Python Tkinter进度条中进行更改

在这里,您可以找到一个示例:

from tkinter import *
from tkinter.ttk import Progressbar
import time


def step():
    for i in range(5):
        ws.update_idletasks()
        pb['value'] += 20
        time.sleep(1)
        txt['text']=pb['value'],'%'

ws = Tk()
ws.title('PythonGuides')
ws.geometry('200x150')
ws.config(bg='#345')


pb = Progressbar(
    ws,
    orient = HORIZONTAL,
    length = 100,
    mode = 'determinate'
    )

pb.place(x=40, y=20)

txt = Label(
    ws,
    text = '0%',
    bg = '#345',
    fg = '#fff'

)

txt.place(x=150 ,y=20 )

Button(
    ws,
    text='Start',
    command=step
).place(x=40, y=50)

ws.mainloop()

相关问题 更多 >