Search code examples
pythontkinterbindframe

Tkinter get frame clicked


In the program bellow, I would like to get which frame is clicked, among the 3. The problem is that when I click, it is always if I was clicking on the last frame.

I use Python 3.9.2 on Windows 10, thanks for the help

from tkinter import *

def click_frame(event):
    print(frame.widget)

fenetre=Tk()

for i in range(0,3):
    if i==0:frame=Frame(width=500,height=50,bg="red")
    if i==1:frame=Frame(width=500,height=50,bg="green")
    if i==2:frame=Frame(width=500,height=50,bg="blue")
    frame.pack_propagate(False)
    frame.widget="frame_"+str(i)
    frame.bind("<Button-1>",click_frame)
    frame.pack()

fenetre.mainloop()

Solution

  • The issue is that the frame you use in click_frame is not an argument of your function so it is the frame after your for loop, i.e. the last frame "frame_2".

    Instead of frame, you should use event.widget which corresponds to the actual widget that triggered the event:

    def click_frame(event):
        print(event.widget.widget)