If you bind a Tkinter widget to an event, normally only the event information is passed to the function responding to the specific event like a mouse click. Python allows you to expand the event handler to include any number of values to be passed on. Here is a typical example ...
Tkinter expanded event handler
# expanding the event handler for a Tkinter button
# to pass other values with the event
try:
# Python2
import Tkinter as tk
except ImportError:
# Python3
import tkinter as tk
class MyApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("expanded event handler")
# use width x height + x_offset + y_offset (no spaces!)
self.geometry("280x200+50+50")
self['bg'] = 'green'
self.createWidgets()
def createWidgets(self):
"""
create a series of buttons
and assign an expanded event handler
"""
for k in range(1, 7):
btn_text = "button%d" % k
btn = tk.Button(self, text=btn_text)
btn.pack(pady=5)
# expanded event handler now contains the button label
# could be other values too
def handler(event, self=self, label=btn_text):
return self.btn_clicked(event, label)
# respond to left mouse click
btn.bind('<1>', handler)
def btn_clicked(self, event, label):
"""action code when button is clicked"""
s = "you clicked button: " + label
self.title(s)
app = MyApp()
app.mainloop()
bvdet 75 Junior Poster
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.