python tkinter 背景色改变不了_python – Tkinter在未聚焦的文本小部件上更改选择背景颜色...

我试图在窗口小部件没有焦点时更改Mac OS X上Tkinter文本窗口小部件中所选文本的默认背景颜色.默认的未聚焦选择颜色为灰色.经过几个小时的搜索,我无法找到一个开箱即用的解决方案来做到这一点.这是我尝试过的:

>使用selectbackground选项更改选择颜色不会在窗口小部件未聚焦时更改选择颜色.例如.它保持灰色.

> Text.tag_configure(“sel”,background = …)也没有

>使用带有“!focus”状态的ttk.Style.map可以对Entry小部件(和其他小部件)起作用,但不适用于Text小部件.

所以我不得不自己动手(见下文).有一个更好的方法吗?

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)

text.bind("", focusout)

# Create an Entry widget to easily test the focus behavior

entry = tk.Entry(root)

entry.pack()

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

root.mainloop()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值