If I produce a Menubutton with checkbuttons created with a list, how can I get the name of the chosen button?

Question:

Ok yes this question is difficultly worded, here is why:

I want to create a menubutton with checkbuttons, created by a list.

tflist = tf.liste
for tf in tflist:
    n1mb.menu.add_checkbutton(label=tf,command=n1change)

n1mb is the menubutton

n1change is a function

def n1change():
    n1mb['text'] = tf

What I want to do, is that the menubutton displays the checked button.

The problem with the shown code is, that if I choose a button, the menubutton is labeled with the last item in the list, not the chosen one.

Asked By: Contrean

||

Answers:

When the checkbuttons are created, you loop through tflist. When this loop is done, tf has the value of the last item in tflist. If you never change tf afterwards, seting n1mb['text'] = tf will always set the text to the last value of tflist.

What you want instead is to “bake-in” the text that you want to set into the command that you set. You can give additional arguments ti a command by using a lambda anonymous function. When you do this in a loop you need to bind the variable in the lambda call. So your command could look like:

command=lambda text=tf: n1change(text)

However, this behavior doesn’t really make sense with checkbuttons, since you can enable and disable them all individually. I’m guessing you actually want radiobuttons, for which only one is activa at all times. A complete example would be:

import tkinter as tk

root = tk.Tk()

v = tk.IntVar()

n1mb = tk.Menubutton(root, text="condiments", relief=tk.RAISED)
n1mb.grid()


def n1change(tf):
    n1mb['text'] = tf


n1mb.menu = tk.Menu(n1mb, tearoff=0)
n1mb["menu"] = n1mb.menu

tflist = ['a', 'b', 'c']

for tf in tflist:
    n1mb.menu.add_radiobutton(label=tf, command=lambda text=tf: n1change(text))

n1mb.pack()
root.mainloop()
Answered By: fhdrsdg
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.