首页 > 解决方案 > python中选项菜单的动态进度条

问题描述

在 Python 中 - 如何使进度条动态化?(如果选择了选项菜单,则更改)例如,如果我在 pl1(选择列表)中选择一个选项,则进度条将更改(假设进度为 20%)。

到目前为止,我尝试过:

from tkinter import *
from tkinter.ttk import Progressbar

pets= {'Cat', 'Dog', 'Fish'}

def __init__(self):

    root =Tk()
    root.title('window')
    root.geometry('1300x690')
    root.resizable(False, False)

    progress = Progressbar(root, orient=HORIZONTAL, length=300, mode='determinate')
    progress.place(x=500, y=15)

    var1 = StringVar(root)
    pl1 = OptionMenu(root, var1, *self.pets)

    pl1.config(width=20, bg="GREEN", fg="white")
    pl1.place(x=470, y=230)

    #Here I want to add 20% progress to the bar if var1 has been selected (no matter what is the 
    value).

    root.mainloop()

谢谢!

标签: pythonuser-interfacetkinterprogress-bar

解决方案


尝试这样的事情:

from tkinter.ttk import Progressbar
import tkinter as tk


def callback(*args):
    # Increment the progressbar's value by 20%
    progressbar["value"] += 20

root = tk.Tk()

progressbar = Progressbar(root, orient="horizontal", length=300)
progressbar.pack()

var = tk.StringVar(root)
pl1 = tk.OptionMenu(root, var, *(1, 2, 3, 4, 5))
pl1.pack()

# Whenever the value of `var` is changed call callback
var.trace("w", callback)

root.mainloop()

我基本上跟踪它的值var以及何时callback调用它。当callback被调用时,它会传入一些我们可以忽略的参数。


推荐阅读