Where To Put Event Handlers And Pass Variables To It?
I've been trying to bind a mouseclick to a grid in a certain frame, after this question I made a new class and bound the event to that, which works. But the function of the mouse e
Solution 1:
You are calling schedule_widgets
from mouse_1
, which is in the namespace of MainApp
, to be able to use it like that use global
keyword.
schedule_widgets = None#-------------------------------------------------------- new ---classSchedule_Label(tk.Label):
def__init__(self, parent, *args, **kwargs):
tk.Label.__init__(self, parent, *args, **kwargs)
self.bind("<Button-1>", mouse_1)
...
classSchedule, this classuses Schedule_Label
classMainApp(tk.Frame):
def__init__(self, parent, *args, **kwargs):
global schedule_widgets #----------------------------------------------- new ---
tk.Frame.__init__(self, parent, *args, **kwargs)
#class schedule is used here
...
schedule_widgets = self.schedule.New(date, stafflist)
...
defmouse_1(event):
global schedule_widgets #--------------------------------------------------- new ---
r = event.widget.grid_info()['row']
c = event.widget.grid_info()['column']
schedule_widgets[(r,c)].configure(state="active")
if __name__ == "__main__":
root = tk.Tk()
app = MainApp(root)
app.pack()
root.mainloop()
There is another way to do it, but schedule_widgets
should be an attribute of MainApp
and when you instantiate schedule_Label
you should give parent reference so that mouse_1
can access schedule_widgets
with parent reference
classSchedule_Label(tk.Label):def__init__(self, parent, *args, **kwargs):
tk.Label.__init__(self, parent, *args, **kwargs)
self.bind("<Button-1>", lambda event, p=parent: mouse_1(event, p)) # --- new ---
...
classSchedule, thisclassusesSchedule_LabelclassMainApp(tk.Frame):def__init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
#class schedule is used here
...
self.schedule_widgets = self.schedule.New(date, stafflist) #------------ new ---
...
defmouse_1(event, parent): #--------------------------------------------------- new ---
r = event.widget.grid_info()['row']
c = event.widget.grid_info()['column']
parent.schedule_widgets[(r,c)].configure(state="active") #------------------ new ---if __name__ == "__main__":
root = tk.Tk()
app = MainApp(root)
app.pack()
root.mainloop()
Post a Comment for "Where To Put Event Handlers And Pass Variables To It?"