首页 > 解决方案 > 如何仅在 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)

请帮帮我

标签: pythontkinter

解决方案


您无需绑定B1-Motion即可完成这项工作,因为您可以轻松获取当前选定的文本。每次选择颜色时,您都可以检查是否有选择。如果没有,您可以简单地更改foregroundText 小部件的属性。如果有,您需要在当前选择上创建一个标签并更改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()

推荐阅读