Python TKinter 进度条标签无法正常工作

时间:2021-01-20 18:30:49

标签: python user-interface tkinter progress

我有一个非常简单的程序,窗口中有两个进度条。我尝试只更新第一个进度条,但第二个进度条标签也会在不应该更新时更新。

我正在使用进度条标签上 this 帖子中 j_4321 的回答。

import tkinter as tk
from tkinter import ttk

root = tk.Tk()


# Progress bar #1
style_1 = ttk.Style(root)
style_1.layout('text.Horizontal.TProgressbar',
               [('Horizontal.Progressbar.trough',
                 {'children': [('Horizontal.Progressbar.pbar',
                                {'side': 'left', 'sticky': 'ns'})],
                  'sticky': 'nswe'}),
                ('Horizontal.Progressbar.label', {'sticky': ''})])
style_1.configure('text.Horizontal.TProgressbar', text='0 %')
variable_1 = tk.DoubleVar(root)
pbar_1 = ttk.Progressbar(root, style='text.Horizontal.TProgressbar', variable=variable_1)
pbar_1.pack()


# Progress bar #2
style_2 = ttk.Style(root)
style_2.layout('text.Horizontal.TProgressbar',
               [('Horizontal.Progressbar.trough',
                 {'children': [('Horizontal.Progressbar.pbar',
                                {'side': 'left', 'sticky': 'ns'})],
                  'sticky': 'nswe'}),
                ('Horizontal.Progressbar.label', {'sticky': ''})])
style_2.configure('text.Horizontal.TProgressbar', text='0 %')
variable_2 = tk.DoubleVar(root)
pbar_2 = ttk.Progressbar(root, style='text.Horizontal.TProgressbar', variable=variable_2)
pbar_2.pack()


def increment():
    # This dosn't change pbar_2's value, as it should act.
    pbar_1.step()

    # Why does this style_1.configure also change the text from style_2 as well???
    style_1.configure('text.Horizontal.TProgressbar', text='{:g} %'.format(variable_1.get()))
    root.after(200, increment)


increment()

root.mainloop()

2 个答案:

答案 0 :(得分:1)

您之所以会出现这种奇怪的行为,是因为您使用了相同的布局。要解决此问题,请更改第二个布局的名称。在这种情况下,我在名称中添加了“1”:'text.Horizontal.TProgressbar1'

style_2 = ttk.Style(root)
style_2.layout('text.Horizontal.TProgressbar1',
               [('Horizontal.Progressbar.trough',
                 {'children': [('Horizontal.Progressbar.pbar',
                                {'side': 'left', 'sticky': 'ns'})],
                  'sticky': 'nswe'}),
                ('Horizontal.Progressbar.label', {'sticky': ''})])
                
style_2.configure('text.Horizontal.TProgressbar1', text='0 %')
variable_2 = tk.DoubleVar(root)

pbar_2 = ttk.Progressbar(root, style='text.Horizontal.TProgressbar1', variable=variable_2)
pbar_2.pack()

答案 1 :(得分:1)

您的两个滚动条都使用名为“text.Horizo​​ntal.TProgressbar”的相同布局。当您更改该布局时,它会更改所有使用该布局的小部件。

您使用 style_1style_2 的事实无关紧要。重要的是您正在配置的布局的名称。