
|
Tkinter Lesson 4 Notes: lambda expressions -- Making functional buttons
- A Button() shortcut
- One way to attach a function to a button is using bind()
btn = Button(root, text = "Click")
btn.bind('<Button-1>', function)
- An easier way to do this is using the command option in Button()
btn = Button(root, text="Click", command=function)
- "command" runs the specified function when the button widget is clicked.
command Example
# A button that changes color
from Tkinter import *
from random import choice
root = Tk()
def colorchange():
colors = ["red", "orange", "yellow", "green"]
a_color = choice(colors)
btn.configure(bg = a_color)
btn = Button(root, text = "Click", command=colorchange)
btn.grid()
- The function name is not in quotes.
- Note the function definition does not take an argument. When using the "command" option in Button(), the function does not receive an event notification.
A problem …
- Neither bind() nor command allows you to send a value to a function (like the name of the button).
- Cannot create a generic function then tell it which button has been pushed.
- If you have lots of buttons (or other widgets), you would have to create a different function definition for each one
- We need a way to bypass these limitations.
The lambda Solution
- A lambda expression is a miniature function.
- lambda functions have two parts:
- Variable definitions
- A single command
- lambda expressions are written :
lambda x = 1, y=2, z=3 : x+y+z
- Syntax:
- The word lambda is a keyword in Python
- Variable definitions are separated by commas
- A colon : separates the variable definitions from the command
lambda is like …
- lambda expressions return a value, so the following are functionally equivalent:
def add(x,y):
return x+y
lambda x,y: x+y
A lambda example
#A button that changes color.
#Same program as earlier, just using lambda
from Tkinter import *
from random import choice
root = Tk()
colors = ["red", "orange", "yellow", "green"]
action = lambda x = colors: btn.configure(bg=choice(x))
btn = Button(root, text = "Click", command=action)
btn.grid()
lambda Limitations
- lambda expressions can have only one command.
- most Python keywords are not available in lambda expressions (I.e. print, for, if, while, def, etc.)
- In Python versions earlier than 2.2, a variable defined outside the lambda expression is not directly available.
- pre Python 2.2:
number = 25
lambda x = number, y= 20: x*y
- Python 2.2 or later
number = 25
lambda y=20: number*y
Creating Many Buttons
- Make a list of button names
button_names = ["dog", "cat", "frog"]
- Make an empty dictionary
dict = {}
- Iterate through the name list, assigning each new name as dictionary key, and the corresponding button as a value.
for name in button_names:
dict[name] = Button(root, text = name)
Passing Values with Buttons
- Use a lambda expression to create mass-produced buttons that send individualized values
list = ["one", "two", "three"]
dict = {}
for num in list:
do_this = lambda x = num: box.insert(x)
dict[num] = Button(root, text = num, command=do_this)
- Be sure to include x=num in the lambda expression, even in later version of Python. This makes sure each button passes its own name.
Example 1 :
from Tkinter import *
root = Tk()
box = Entry(root, width=30)
box.grid(row=0, column=0, columnspan=5)
def boxupdate(critter):
length=len(box.get())
box.delete(0, length)
box.insert(0, critter)
dict = {}
col = 0
words = ["Tiger", "Parrot", "Elephant", "Mouse", "Python"]
for animal in words:
action = lambda x =animal: boxupdate(x)
dict[animal] = Button(root, text=animal, command=action)
dict[animal].grid(row=1, column = col)
col += 1
Example 2:
""" Buttons randomly change color when clicked"""
from Tkinter import *
from random import choice
root = Tk()
root.title("ColorPad")
# Random hex-color generator
def newcolor():
colorchoices = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
hexnum = '#'
for x in range(0,6):
hexnum += choice(colorchoices)
return hexnum
# Make Buttons
list = ["One", "Two", "Three", "Four"]
col = 0
row = 1
dict = {}
for item in list:
action = lambda x = item: dict[x].configure(bg=newcolor(), fg=newcolor())
dict[item] = Button(root, text = item, width=4, command = action)
dict[item].grid(row = row, column = col, padx=2, pady=2, sticky=EW)
col += 1
if col % 2 ==0:
col = 0
row +=1
Restricted access |