ウィジェットにフォーカスがない場合、 Mac OS X の Tkinter Text ウィジェットで選択したテキストのデフォルトの背景色を変更しようとしています。デフォルトのフォーカスされていない選択色は灰色です。何時間も検索した後、これを行うためのすぐに使えるソリューションを見つけることができませんでした。これが私が試したことです:
- オプションで選択色を変更して
selectbackground
も、ウィジェットがフォーカスされていない場合、選択色は変更されません。例: 灰色のままです。 - そうでもない
Text.tag_configure("sel", background=...)
- 状態での使用
ttk.Style.map
は"!focus"
エントリ ウィジェット (およびその他) で機能しますが、テキスト ウィジェットでは機能しません。
そのため、自分でロールする必要がありました (以下を参照)。これを行うより良い方法はありますか?
import Tkinter as tk
# Replace 'tag_out' with 'tag_in'
def replace_tag(widget, tag_out, tag_in):
ranges = widget.tag_ranges(tag_out)
widget.tag_remove(tag_out, ranges[0], ranges[1])
widget.tag_add(tag_in, ranges[0], ranges[1])
def focusin(e):
replace_tag(e.widget, "sel_focusout", "sel")
def focusout(e):
replace_tag(e.widget, "sel", "sel_focusout")
root = tk.Tk()
# Create a Text widget with a red selected text background
text = tk.Text(root, selectbackground="red")
text.pack()
# Add some text, and select it
text.insert("1.0", "Hello, world!")
text.tag_add("sel", "1.0", "end")
# Create a new tag to handle changing the background color on selected text
# when the Text widget loses focus
text.tag_configure("sel_focusout", background="green")
replace_tag(text, "sel", "sel_focusout")
# Bind the events to make this magic happen
text.bind("<FocusIn>", focusin)
text.bind("<FocusOut>", focusout)
# Create an Entry widget to easily test the focus behavior
entry = tk.Entry(root)
entry.pack()
entry.insert("0", "Focus me!")
root.mainloop()