Обновление метки кнопок Menubutton в Tkinter - PullRequest
0 голосов
/ 08 мая 2018

Я бы хотел обновить текст метки кнопок в меню, используя функцию обновления при нажатии кнопки.

До сих пор я справлялся с этим, удаляя целые кнопки и воссоздавая их, но это не работает идеально и добавляет ненужную сложность. Вот то, что я имею до сих пор:

from Tkinter import *

INGREDIENTS = ['cheese','ham','pickle','mustard','lettuce']


def print_ingredients(*args):
   values = [(ingredient, var.get()) for ingredient, var in data.items()]
   print values

results = []

def update():

    values = [(ingredient, var.get()) for ingredient, var in data.items()]

    for value in values:
        if value[1] == 1:
            results.append(value[0])
    print results

    for value in values:
        mb.menu.delete(0)

    for ingredient in INGREDIENTS:


        if ingredient in results:
            on_val = 0
            off_val = 1
            click = "Clicked!"
        else:
            on_val = 1
            off_val = 0
            click = ""

        var = IntVar()
        mb.menu.add_checkbutton(label=ingredient + " " + click, variable=var, onvalue = on_val, offvalue = off_val, command = update)
        data[ingredient] = var # add IntVar to the dictionary


data = {} # dictionary to store all the IntVars

top = Tk()

mb=  Menubutton ( top, text="Ingredients", relief=RAISED )
mb.menu  =  Menu ( mb, tearoff = 0 )
mb["menu"]  =  mb.menu

for ingredient in INGREDIENTS:
    var = IntVar()
    mb.menu.add_checkbutton(label=ingredient, variable=var, command = update)
    data[ingredient] = var # add IntVar to the dictionary

btn = Button(top, text="Print", command=print_ingredients)
btn.pack()

mb.pack()

top.mainloop()

Есть ли способ обновить текст метки кнопки-флажка в меню?

1 Ответ

0 голосов
/ 08 мая 2018

Вы можете trace переменные, которые вы прикрепили к кнопкам.Если вы называете переменные после ингредиентов и сохраняете их в формате dict, вы можете получить ингредиент и переменную в обратном вызове трассы и изменить запись с нужным индексом:

from Tkinter import *

INGREDIENTS = ['cheese','ham','pickle','mustard','lettuce']

def update(var_name, *args):
    # Beacause we defined names for the BooleanVars, the first argument is the name of the changed Var
    # We named the Vars after the ingredients
    ingredient = var_name
    # Get the actual var from the dict
    var = data[var_name]
    # Get the index of the clicked ingredient
    i = INGREDIENTS.index(ingredient)
    # Check wether the checkbutton is clicked on or not
    if var.get() == True:
        # If checked, change label to include 'Clicked'
        mb.menu.entryconfigure(i, label = ingredient + ' Clicked!')
    else:
        # If unchecked, change label to just ingredient
        mb.menu.entryconfigure(i, label = ingredient)

data = {} # dictionary to store all the IntVars

top = Tk()

mb=  Menubutton ( top, text="Ingredients", relief=RAISED )
mb.menu  =  Menu ( mb, tearoff = 0 )
mb["menu"]  =  mb.menu

for ingredient in INGREDIENTS:
    # Create a Boolean variable with the name of the ingredient
    var = BooleanVar(name = ingredient)
    # Trace changes to the variable
    var.trace("w", update)
    # Create Checkbutton without command
    mb.menu.add_checkbutton(label=ingredient, variable=var)
    # Add variable to the dictionary
    data[ingredient] = var

mb.pack()

top.mainloop()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...