使用标签将所选文本设置为粗体
问题内容:
我一直在尝试制作一个简单的文本编辑器,并一直在尝试使用标签。我已经能够使用标签创建证明。现在,我添加了一个粗体选项。
我的问题是我找不到使用"sel"
标签(当前选择中使用的标签)的许多示例。
每当我使用SEL
标签时,只要突出显示该文本,该文本就仅是粗体;当不突出显示该文本时,它将恢复为旧的紧字体。
这是我的代码的一小部分:
def Bold(self, body, Just, Line, selected font):
bold font = tkFont.Font(family=selectedfont, weight="bold")
selected font = boldfont
body.tag_config("sel",font=selectedfont)
body.tag_add("sel", 1.0,END)
当Bold
按下按钮时,先前的函数被调用。现在,我具有body.tag_add("sel", 1.0, END)
从1.0
到的集合END
,因为我不知道如何获取所选域。我已经尝试过了<<Selection>>
,但是经过很长一段时间的尝试,对我没有帮助。
问题答案:
您只需要tag_add()
在函数内部:
import Tkinter as tk
def make_bold():
aText.tag_add("bt", "sel.first", "sel.last")
lord = tk.Tk()
aText = tk.Text(lord, font=("Georgia", "12"))
aText.grid()
aButton = tk.Button(lord, text="bold", command=make_bold)
aButton.grid()
aText.tag_config("bt", font=("Georgia", "12", "bold"))
lord.mainloop()
我
在一个完全无关的搜索中偶然发现了一个非常有教育意义的例子,莫过于Bryan
Oakley
!
这是更动态替代方案的快速示例:
import Tkinter as tk
import tkFont
def make_bold():
current_tags = aText.tag_names("sel.first")
if "bt" in current_tags:
aText.tag_remove("bt", "sel.first", "sel.last")
else:
aText.tag_add("bt", "sel.first", "sel.last")
lord = tk.Tk()
aText = tk.Text(lord, font=("Georgia", "12"))
aText.grid()
aButton = tk.Button(lord, text="bold", command=make_bold)
aButton.grid()
bold_font = tkFont.Font(aText, aText.cget("font"))
bold_font.configure(weight="bold")
aText.tag_configure("bt", font=bold_font)
lord.mainloop()