List Comprehension to Create Multiple Buttons


An approach to create multiple GUI buttons (or other widgets) using list comprehension. In this case I used the Tkinter GUI toolkit that comes with the Python installation.

exploring Tkinter buttons
create multiple buttons using list comprehension
also use a class approach to Tkinter
tested with Python27 and Python33 by  vegaseat  04dec2012

from functools import partial
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

class Gui(tk.Tk):
    def __init__(self):
        # the root will be self
        self.title('right/left click buttons')
        self.label = tk.Label(self, width=20, bg='blue', fg='yellow',
                              font='times 12 bold')
        self.label.pack(padx=35, pady=3)
        self.button_labels = ['red', 'green', 'magenta', 'yellow']
        # create buttons using a list comprehension
        self.buttons = [tk.Button(self, width=20, text=label,
                        command=partial(self.do_command, ix, label)) \
                        for ix, label in enumerate(self.button_labels)]
        #print(self.buttons)  # test
        # lay out the buttons
        for button in self.buttons:
        # command responds to the left mouse click
        # optionally bind the buttons to an action on
        # clicking the right mouse button
        for ix, button in enumerate(self.buttons):
            button.bind('<Button-3>', partial(self.do_binding, ix))

    def do_command(self, ix, label):
        # test print()
        print('command ix={0} label={1}'.format(ix, label))
        # in this case color info is in label
        self['bg'] = label
        # use index ix to do something from a list

    def do_binding(self, ix, event):
        # get background color of button clicked
        bg_color = event.widget['bg']
        # test print()
        print('binding ix={0} bg={1}'.format(ix, bg_color))
        # use ix to show current button label
        self.label['text'] = self.button_labels[ix]

    def run(self):

# test the potential module
if __name__ == '__main__':

Here we create radiobuttons with list comprehension:

explore Tkinter's Radiobutton widget
create muliple radio buttons with list comprehension


    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

def click():
    """shows the value of the radio button selected"""

root = tk.Tk()

# create a labeled frame for the radiobuttons
# relief='groove' and labelanchor='nw' are default
labfr = tk.LabelFrame(root, text=" select one ", bd=3)
labfr.pack(padx=55, pady=10)

# use a string variable
vs = tk.StringVar()

values = ['eggs', 'spam', 'cheese', 'bacon']
# create a list of Radiobutton instances
radiobuttons = [tk.Radiobutton(labfr, text=val, value=val,
    variable=vs, command=click) for val in values]

# use the pack() layout manager to position the radio buttons
[rb.pack(anchor='w') for rb in radiobuttons]

# needed, set to None or any of the radiobutton values
# show value set
if vs:

Isn't it about time forums rewarded their contributors?

Earn rewards points for helping others. Gain kudos. Cash out. Get better answers yourself.

It's as simple as contributing editorial or replying to discussions labeled or OP Kudos

This is an OP Kudos discussion and contributors may be rewarded
Start New Discussion
Tags Related to this Article