8
我試圖更改所選文本的默認背景顏色在Mac OS X 一個Tkinter的文本小部件時,窗口小部件沒有焦點選擇背景色。默認未聚焦的選擇顏色是灰色的。經過許多小時的搜索之後,我無法找到開箱即用的解決方案來執行此操作。以下是我所嘗試的:Tkinter的改變上產生模糊文本小
- 使用
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()
Windows有相反的問題;默認情況下,沒有不活動的選擇背景。爲了讓它在Windows上保持灰色,Idle對這個與你類似的'錯誤'有一個解決方法。最近有人指出'inactiveselectbackground',所以我今天解決了這個解決方法(我希望我已經搜索過並且在一年前發現了這個)。該選項記錄在https://www.tcl.tk/man/tcl8.5/TkCmd/text.htm#M-inactiveselectbackground。我正在考慮擴展不完整的tkinter文檔。 – 2015-09-27 21:33:06