bendl bendl - 1 month ago 11
Python Question

Making a list of mouse over event functions in Tkinter

I'm making a GUI for a medical tool as a class project. Given a condition, it should output a bunch of treatment options gathered from different websites like webMD. I would like to be able to handle mouseover events on any of the treatments listed to give a little more information about the treatment (such as the category of drug, whether it is a generic or not, etc).

The labels are stored in a list, as I have no idea how many different treatments will be returned beforehand. So my question is how can I make these mouseover events work. I can't write a function definition for every single possible label, they would number in the hundreds or thousands. I'm sure there's a very pythonic way to do it, but I have no idea what.

Here's my code for creating the labels:

def search_click():
"""
Builds the search results after the search button has been clicked
"""
self.output_frame.destroy() # Delete old results
build_output() # Rebuild output frames
treament_list = mockUpScript.queryConditions(self.condition_entry.get()) # Get treatment data
labels = []
frames = [self.onceFrame, self.twiceFrame, self.threeFrame, self.fourFrame] # holds the list of frames
for treament in treament_list: # For each treatment in the list
label = ttk.Label(frames[treament[1] - 1], text=treament[0]) # Build the label for treatment

labels.append(label) # Add the treatment to the list
label.pack()


and here is what the GUI looks like (don't judge [-; )GUI image

The text "Hover over drugs for information" should be changed depending on which drug your mouse is hovering over.

Answer

I can't write a function definition for every single possible label, they would number in the hundreds or thousands. I'm sure there's a very pythonic way to do it, but I have no idea what.

Check out lambda functions which are nearly identical to what you want.

In your case, something like:

def update_bottom_scroll_bar(text):
    # whatever you want to do to update the text at the bottom

for treatment in treament_list:  # For each treatment in the list
    label = ttk.Label(frames[treatment[1] - 1], text=treatment[0])  # Build the label for treatment

    label.bind("<Enter>", lambda event, t=treatment: update_bottom_scroll_bar(text=t))
    label.bind("<Leave>", lambda event: update_bottom_scroll_bar(text='Default label text'))

    labels.append(label)  # Add the treatment to the list
    label.pack()

Also please spell your variables right, I corrected treament to treatment...