根据文本小部件中的变量应用标签

时间:2017-07-14 22:40:07

标签: python tkinter tags

我正在尝试为temp变量着色,但没有运气:

from Tkinter import *
root = Tk()
text = Text(root)
temp='Hello'
text.insert(INSERT, "Hello %s" %temp)
text.pack()
x=1
y=10
text.tag_add("tag1", "1.4", "@%d,%d" %(x, y))
text.tag_config("tag1", background="blue", foreground="yellow")
root.mainloop()

除了可行的方法之外,有没有办法使用变量xy来指定索引?我认为这可以解决我的问题。

Python 2.7 - Windows

1 个答案:

答案 0 :(得分:1)

好吧,我可以这样做来使用变量来设置索引。

from tkinter import *

root = Tk()

text = Text(root)
temp='Hello'
text.insert(INSERT, "Hello %s" %temp)
text.pack(expand=1, fill=BOTH)

text.tag_configure("BOLD", foreground='green')
def get_start():
    x=1
    y=1
    return '%d.%d' %(x,y)
def get_end():
    x=1
    y=7
    return '%d.%d' %(x,y) 
def test():
    text.tag_add("BOLD", get_start(), get_end())

bold_btn = Button(root, text="Bold", command=test)
bold_btn.pack(side="left")


root.mainloop()