'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 1:[1]
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)
Solution 2:[2]
Additionally to the answer of @j_4321, you can use an array with the color names instead of the if statements. So your complete code would look like this:
from tkinter import *
def click_frame(event):
print(event.widget.widget)
fenetre = Tk()
for color in ["red", "green", "blue"]:
frame = Frame(width=500, height=50, bg=col)
frame.pack_propagate(False)
frame.widget = "frame_" + i
frame.bind("<Button-1>", click_frame)
frame.pack()
fenetre.mainloop()
Solution 3:[3]
thank you for your answer. But after posting I fond out a shortcut to solve the problem: I removed the "for in loop" and I used the code individually for each frame, ex:
apple_frame = Frame(width=500, height=50, bg=col)
apple_frame.widget = "apple_frame"
apple_frame.bind("<Button-1>", click_frame)
Each time I click in a new frame, frame name is printed. Have a great day!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | j_4321 |
Solution 2 | |
Solution 3 | pkanda |