python - 如何仅在 tkinter 中更改所选文本的属性
问题描述
此代码更改您输入的文本的颜色
from tkinter import*
from tkinter.colorchooser import*
def getColor():
color = askcolor()
text['fg'] = color[1]
root=Tk()
text=Text(root)
text.pack()
king=Menu(root)
root.config(menu=king)
view= Menu(king,tearoff = 0)
view2=Menu(view,tearoff=0)
view2.add_command(label='Color',command=getColor)
view.add_cascade(label='Text',menu=view2)
king.add_cascade(label="View",menu=view)
但我需要更改选定的文本。例如,我们输入文本“Hello my name's Alex”,将整个文本的颜色更改为红色,然后选择单词“Alex”并仅更改其颜色。也许这里有必要申请,但我不知道如何
text.bind ('<B1-Motion>')
text.tag_add(SEL_FIRST,SEL_LATS)
请帮帮我
解决方案
您无需绑定B1-Motion
即可完成这项工作,因为您可以轻松获取当前选定的文本。每次选择颜色时,您都可以检查是否有选择。如果没有,您可以简单地更改foreground
Text 小部件的属性。如果有,您需要在当前选择上创建一个标签并更改foreground
标签的。但是,每次执行此操作时都需要创建一个新的标签名称,以防止更改先前选择的颜色,您可以使用一个简单的计数器来添加到标签名称中。
在代码中,它可能如下所示:
from tkinter import *
from tkinter.colorchooser import *
def getColor():
global count
color = askcolor()
if text.tag_ranges('sel'):
text.tag_add('colortag_' + str(count), SEL_FIRST,SEL_LAST)
text.tag_configure('colortag_' + str(count), foreground=color[1])
count += 1
else:
# Do this if you want to overwrite all selection colors when you change color without selection
# for tag in text.tag_names():
# text.tag_delete(tag)
text.config(foreground=color[1])
root=Tk()
text=Text(root)
text.pack()
count = 0
king=Menu(root)
root.config(menu=king)
view= Menu(king, tearoff=0)
view2=Menu(view, tearoff=0)
view2.add_command(label='Color',command=getColor)
view.add_cascade(label='Text', menu=view2)
king.add_cascade(label='View', menu=view)
root.mainloop()
推荐阅读
- javascript - HTML,当内容达到一定高度时如何制作可重复的页眉和页脚?
- ibm-mq - IBM MQ 使用 amqsgetc 失败,原因为“2058”
- html - 如何刷新 Aurelia 中的子组件以撤消表单?
- postman - POSTMAN ENV FILE,同一对象的不同值
- json - 将环境变量从 json 传递到库
- http - HTTPS 上的 Atmosphere Websockets
- android-fragments - android,片段的 getArguments() 是否总是返回为此片段设置的参数,即使在片段被销毁后也是如此?
- android - Room - 为什么使用 @Relation 而不是 @ForeignKey?
- node.js - 最后如何设置 mongo db,以便我可以在 Windows 上将它与 node Js 一起使用
- mysql - 在远程服务器上运行 Django,如何在浏览器中查看