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.
List Comprehension to Create Multiple Buttons
''' 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
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.