Python Tkinter Clickable Text?

时间:2016-01-21 14:49:56

标签: text colors tkinter click bind

我想知道是否有办法在Tkinter中制作可点击的文字。也许就像你会在游戏的标题屏幕上看到的那样,以及将鼠标悬停在文本上的位置,它会改变颜色/高光本身。我需要点击才能执行另一个功能。

这些事情中的任何一个都可能吗?谢谢!

1 个答案:

答案 0 :(得分:3)

您正在寻找tkinter的活动:

tk_widget.bind("<Button-1>",CALLBACK)

回调需要接受一个事件参数,该参数是一个包含有关触发事件的信息的字典。

这可能会遇到重叠的小部件问题,例如画布中的窗口或标签有时会触发其背后窗口的回调。

将鼠标悬停在窗口小部件上时,事件被称为"<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()

希望这有助于:)