您正在寻找 tkinter 的活动:
tk_widget.bind("<Button-1>",CALLBACK)
Run Code Online (Sandbox Code Playgroud)
回调需要接受一个事件参数,该参数是一个字典,其中包含有关触发事件的信息。
这可能会遇到重叠小部件的问题,例如画布中的窗口或标签有时会触发其后面窗口的回调。
对于将鼠标悬停在小部件上,将调用该事件,"<Enter>"并将鼠标移出小部件区域以"<Leave>"突出显示文本效果,如果您只想捕获窗口上任意位置的单击,然后在根调用上root.bind_all("<Button-1>",CALLBACK)
来源:http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/events.html
例子:
try:
import tkinter as tk
except ImportError:
import Tkinter as tk
def change_case(event=None):
new_text = str.swapcase(lab["text"])
lab.config(text=new_text)
def red_text(event=None):
lab.config(fg="red")
def black_text(event=None):
lab.config(fg="black")
root = tk.Tk()
lab = tk.Label(root,text="this is a test")
lab.bind("<Button-1>",change_case)
lab.bind("<Enter>",red_text)
lab.bind("<Leave>",black_text)
lab.grid()
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助 :)