List Comprehension to Create Multiple Buttons

vegaseat 2 Tallied Votes 474 Views Share

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.

''' tk_button_loop3.py
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
try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

class Gui(tk.Tk):
    def __init__(self):
        # the root will be self
        tk.Tk.__init__(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:
            button.pack(pady=3)
        # 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
        print(self.buttons[ix])

    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):
        self.mainloop()


# test the potential module
if __name__ == '__main__':
    Gui().run()
Ene Uran 638 Posting Virtuoso

Here we create radiobuttons with list comprehension:

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

'''

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

def click():
    """shows the value of the radio button selected"""
    root.title(vs.get())

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
vs.set('spam')
# show value set
if vs:
    click()

root.mainloop()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.