首页 > 解决方案 > Python进度条选择限制

问题描述

我正在使用带有进度条的 Tkinter。

我在下面的代码中添加了 50% 到我的进度条的“回调”函数。我想将功能限制为每个 OptionMenu selection 只工作一次

目前,我可以在第一个 OptionMenu 上单击两次并在进度栏中达到 100%。有谁知道我应该在“回调”函数中更改什么以使其对每个 OptionMenu 仅工作一次?无论用户单击多少次来更改其选定值。

在此处输入图像描述

from tkinter import *
from tkinter.ttk import Progressbar

root = Tk()
root.title('Input window V1')
root.geometry('600x400')
root.resizable(False, False)

frame = Frame(root, width=600, height=400)
frame.configure(background="gray28")
frame.pack(fill=BOTH, expand=True)

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

Budget = {'Flexible', 'Variable', 'Fixed'}
Commitment = {'High', 'Medium', 'Low'}

def callback(*args):
    progress["value"] += 50

bottom_header = Label(root, bg="gray28", fg="white", pady=3,
                  font=("Helvetica", 20, 'underline'), text='Please fill the following attributes:')
bottom_header.place(x=110, y=100)

lbl1 = Label(root, bg="gray28", text='Budget:', fg="cyan2", font=("Helvetica", 14))
lbl1.place(x=120, y=200)

lbl2 = Label(root, bg="gray28", text='Commitment:', fg="cyan2", font=("Helvetica", 14))
lbl2.place(x=120, y=240)

var1 = StringVar(root)
pl1 = OptionMenu(root, var1, *Budget)
pl1.config(width=20, bg="GREEN", fg="white")
pl1.place(x=250, y=200)

var1.trace("w", callback)

var2 = StringVar(root)
pl2 = OptionMenu(root, var2, *Commitment)
pl2.config(width=20, bg="GREEN", fg="white")
pl2.place(x=250, y=240)

var2.trace("w", callback)

global var_dict

var_dict = dict(Budget=var1,
                Commitment=var2)

button1 = Button(root, text="Test")
button1.config(width=25, bg="white")
button1.place(x=220, y=320)

root.mainloop()

提前致谢!

标签: pythonuser-interfacetkinterprogress-bar

解决方案


试试这个:

from tkinter import *
from tkinter.ttk import Progressbar

def callback(*args):
    user_input = (var_1.get(), var_2.get()) # Here you can add even more variables
    value = 100 - 100/len(user_input)*(user_input.count("")+user_input.count("Select option"))
    progress.config(value=value)

root = Tk()

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

var_1 = StringVar(root)
var_1.trace("w", callback)

optionmenu_1 = OptionMenu(root, var_1, "Select option", "Option 1", "Option 2")
optionmenu_1.pack()

var_2 = StringVar(root)
var_2.trace("w", callback)

optionmenu_2 = OptionMenu(root, var_2, "Select option", "Option 1", "Option 2")
optionmenu_2.pack()

# You can remove these if you don't like them:
var_1.set("Select option")
var_2.set("Select option")

root.mainloop()

它计算空OptionMenus 的数量并将进度条设置为正确的百分比。


推荐阅读