我怎样才能做一些事情,比如粗体/突出显示/只更改我选择的文本上的字体



我正在制作一个简单的文字处理器,我希望能够只更改我突出显示的文本的字体/样式(或任何名称(。

不能说我尝试过什么,因为我什至不知道从哪里开始。

from tkinter import *
# window setup
tk = Tk()
# main textbox
textbox = Text(tk)
textbox.configure(width=85,height=37)
textbox.grid(column=0,row=0,rowspan=500)
# bold
def bold():
    textbox.config(font=('Arial',10,'bold'))
bBut = Button(tk,text='B',command=bold)
bBut.configure(width=5,height=1)
bBut.grid(column=0,row=0)
tk.mainloop()

我可以将整个文本更改为粗体/斜体/等,但我希望能够指定其中的一部分。

它使用tags为文本分配颜色或字体

import tkinter as tk
def set_bold():
    try:
        textbox.tag_add('bold', 'sel.first', 'sel.last')
    except Exception as ex:
        # text not selected
        print(ex)
def set_red():
    try:
        textbox.tag_add('red', 'sel.first', 'sel.last')
    except Exception as ex:
        # text not selected
        print(ex)
root = tk.Tk()
textbox = tk.Text(root)
textbox.pack()
textbox.tag_config('bold', font=('Arial', 10, 'bold'))
textbox.tag_config('red', foreground='red')
button1 = tk.Button(root, text='Bold', command=set_bold)
button1.pack()
button2 = tk.Button(root, text='Red', command=set_red)
button2.pack()
root.mainloop()

最新更新