说明 :
我有一个文本小部件,其中包含一些文本。 我想要一个单词的工具提示。例如,对于特定单词,工具提示#1,对于其他单词,工具提示#2,依此类推。 当我尝试为单个单词创建一个工具提示时,实际上为整个文本小部件创建了一个工具提示。我知道原因是因为我将Text小部件传递给了HoverInfo类。
我的问题:
我的 说明 的代码:
from tkinter import *
import re
import tkinter as tk
class HoverInfo(Menu):
def __init__(self, parent, text, command=None):
self._com = command
Menu.__init__(self,parent, tearoff=0)
if not isinstance(text, str):
raise TypeError('Trying to initialise a Hover Menu with a non string type: ' + text.__class__.__name__)
toktext=re.split('\n', text)
for t in toktext:
self.add_command(label = t)
self._displayed=False
self.master.bind("<Enter>",self.Display )
self.master.bind("<Leave>",self.Remove )
def __del__(self):
self.master.unbind("<Enter>")
self.master.unbind("<Leave>")
def Display(self,event):
if not self._displayed:
self._displayed=True
self.post(event.x_root, event.y_root)
if self._com != None:
self.master.unbind_all("<Return>")
self.master.bind_all("<Return>", self.Click)
def Remove(self, event):
if self._displayed:
self._displayed=False
self.unpost()
if self._com != None:
self.unbind_all("<Return>")
def Click(self, event):
self._com()
def HelloWorld():
print('Hello World')
def vp_start_gui():
global val, w, root, o
root = Tk()
canvas = tk.Canvas(root)
scroll = tk.Scrollbar(root, orient='horizontal', command=canvas.xview)
canvas.configure(xscrollcommand=scroll.set)
frame = tk.Frame(canvas) # frame does not get pack() as it needs to be embedded into canvas throught canvas.
scroll.pack(side='bottom', fill='x')
canvas.pack(fill='both', expand='yes')
canvas.create_window((0,0), window=frame, anchor='nw')
frame.bind('<Configure>', lambda x: canvas.configure(scrollregion=canvas.bbox('all'))) # lambda function
journal = tk.Text(frame, width = 75, height = 39)
journal.configure(background="#f2f2f2")
journal.configure(borderwidth="3")
journal.configure(relief="groove")
journal.grid() # grid instead
journal.insert("end", "I want tooltip over this text only")
hover = HoverInfo(journal,'while hovering press return \n for an exciting msg', HelloWorld)
root.mainloop()
if __name__ == '__main__':
vp_start_gui()
答案 0 :(得分:1)
您可以将标签添加到文本小部件中的一系列字符。然后,您可以将鼠标事件<Enter>
和<Leave.
绑定到这些标签。
这是一个非常人为的例子:
import tkinter as tk
def show_info(text):
label.configure(text=text)
root = tk.Tk()
text_widget = tk.Text(root)
label = tk.Label(root)
label.pack(side="top", fill="x")
text_widget.pack(fill="both", expand=True)
for color in ("red", "orange", "yellow", "green", "blue", "indigo", "violet"):
tag = color
text = color
text_widget.insert("end", text+"\n", (tag, ))
text_widget.tag_configure(tag, background=color, foreground="white")
text_widget.tag_bind(tag, "<Enter>",
lambda event, color=color: show_info(color))
text_widget.tag_bind(tag, "<Leave>",
lambda event, color=color: show_info(""))
tk.mainloop()