簡體   English   中英

如何僅在tkinter中更改所選文本的屬性

[英]How to change the properties of selected text only in 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屬性。 如果存在,則需要在當前選擇上創建標簽並更改標簽的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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM