python tkinter 使用(六)

发布时间 2023-12-26 20:16:34作者: 夏沫琅琊

python tkinter 使用(六)

本文主要讲述tkinter中进度条的使用。

1:确定的进度条

progressbar = tkinter.ttk.Progressbar(root, mode="determinate", maximum=100, value=0)
progressbar.pack()

def updateProgressBar():
    for i in range(100):
        progressbar['value'] = i + 1
        root.update()
        time.sleep(0.1)


button = tkinter.Button(root, text='Running', command=updateProgressBar)
button.pack()
  1. ttk.Progressbar来创建确定进度条;

  2. mode设置为:determinate;

  3. 设置maximumvalue属性来控制进度条的进度。

  4. root.update()来更新绘制页面

2:不确定的进度条

progress = tkinter.ttk.Progressbar(root, length=200, mode="indeterminate", orient=tkinter.VERTICAL)
progress.pack()


def start():
    # 开始进度条
    progress.start()


def stop():
    #结束
    progress.stop()

button = tkinter.Button(root, text='start', command=start)
button.pack(side=tk.LEFT)
button = tkinter.Button(root, text='stop', command=stop)
button.pack(side=tk.RIGHT)

3:自定义样式的progressbar

通过ttk.Style来自定义进度条的样式,例如修改进度条的颜色、背景色。

#样式自定义进度条
style = ttk.Style()
style.configure('red.Horizontal.TProgressbar', foreground='black', background='red')
custom = ttk.Progressbar(root, style='red.Horizontal.TProgressbar', mode='determinate', maximum=100, value=0)
custom.pack()

# 更新进度条
def update():
    for i in range(100):
        custom['value'] = i
        root.update()
        time.sleep(0.1)
    custom['value'] = 0

# 创建按钮
btn = tk.Button(root, text='StartStyle', command=update)
btn.pack()

red.Horizontal.TProgressbar是一个基于Progressbar的自定义样式,用于创建一个水平方向的进度条,前景色和背景色都是红色。