tkinter报告框架以及鼠标坐标

时间:2013-04-10 10:05:32

标签: python-3.x tkinter

 def mouse_click(event):
    #'reports' to both terminal and results text box
    parent_name = Frame.winfo_parent(root)
    parent = Frame._nametowidget(parent_name)
    result = ("{0}: {1},{2}\n ".format('Clicked at', event.x, event.y))
    print('clicked at',parent,  event.x, event.y)

from tkinter import *


root = Tk()
root.title("Change Text")
root.geometry('700x500')

top=root.winfo_toplevel()
for rn in range(0,9): # rn = row number
    top.rowconfigure(rn, weight=1)
top.rowconfigure(rn, weight=0)    
for cn in range(0,5): # cn = column number
    top.columnconfigure(cn, weight=1)
# FRAME 1
frame1 = Frame(root,  borderwidth = 2, background = '#EFE0CD', relief = RIDGE,width = 25, height = 20)
frame1.bind("<Button-1>", mouse_click)
frame1.grid(column = 0, row = 0, columnspan = 2, rowspan = 3, sticky = N+S+E+W)
frame1_lbl = Label(frame1, text='Frame 1', font='comic-sans-MS 10 ', fg ='red', bg = '#EFE0CD')
frame1_lbl.grid(row=0, column =0)

# FRAME 2
frame2 = Frame(root,  borderwidth = 2, background = '#CCC6B0', relief = RIDGE,width = 25, height = 20)
frame2.bind("<Button-1>", mouse_click)
frame2.grid(column = 0, row = 3, columnspan = 2, rowspan = 3, sticky = N+S+E+W)
frame2_lbl = Label(frame2, text='Frame 2', font='comic-sans-MS 10', fg ='red', bg = '#CCC6B0')
frame2_lbl.grid(row=0, column =0,)
root.mainloop()

我知道这是一个非常愚蠢的问题。如何识别单击鼠标的框架,以便报告在x y坐标处打印单击的frame1或frame2?我发现有一些关于使用winfo_parent但显然没有正确使用它。 谢谢

1 个答案:

答案 0 :(得分:0)

传递给回调的事件对象具有widget属性,该属性是对获取事件的窗口小部件的引用。因此,event.widget是您要打印的内容。