您可以使用带有SAPI SpVoice的pywin32
包.
我已经将<Enter>
属性绑定为每当您将鼠标悬停在标签上时发言.当然,如果您愿意,您可以使用不同的触发器.
import tkinter as tk
import win32com.client
# create root window
root = tk.Tk()
root.title("Test")
lbl = tk.Label(root, text="A label")
lbl.grid()
speaker = win32com.client.Dispatch("SAPI.SpVoice")
lbl.bind("<Enter>", lambda _: speaker.Speak(lbl.cget("text")))
root.mainloop()
如果您想对此解决方案进行泛化,以便对所有标签进行说明,则可以将tk.Label
作为子类,如下所示
import tkinter as tk
import win32com.client
speaker = win32com.client.Dispatch("SAPI.SpVoice")
class NarratedLabel(tk.Label):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.bind("<Enter>", lambda _: speaker.Speak(self.cget("text")))
# create root window
root = tk.Tk()
root.title("Test")
lbl = NarratedLabel(root, text="A label")
lbl.grid()
lbl2 = NarratedLabel(root, text="Another label")
lbl2.grid()
root.mainloop()