Tkinter更改未聚焦文本widg上的选定背景色

2024-06-17 12:47:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试更改Mac OS X上的Tkinter文本小部件中选定文本的默认背景色,但该小部件没有焦点。默认的未聚焦选择颜色为灰色。经过几个小时的搜索,我找不到一个现成的解决方案。以下是我尝试过的:

  • 使用selectbackground选项更改选择颜色不会在小部件未聚焦时更改选择颜色。E、 它保持灰色。
  • 也不是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()

Tags: thetext文本部件tagrootwidgetout
1条回答
网友
1楼 · 发布于 2024-06-17 12:47:31

从Tk源代码中挖掘出答案!inactiveselectbackground选项设置颜色。

import Tkinter as tk

root = tk.Tk()

# Create a Text widget with a red selected text background
# And green selected text background when not focused
text = tk.Text(root, selectbackground="red", inactiveselectbackground="green")
text.pack()

# Add some text, and select it
text.insert("1.0", "Hello, world!")
text.tag_add("sel", "1.0", "end")

# Create an Entry widget to easily test the focus behavior
entry = tk.Entry(root)
entry.pack()

entry.insert("0", "Focus me!")

root.mainloop()

相关问题 更多 >