【问题标题】:How can I do things like bold/highlight/change the font on only the text that I select?如何仅在我选择的文本上执行粗体/突出显示/更改字体之类的操作?
【发布时间】:2019-07-17 18:54:28
【问题描述】:

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

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

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()

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

【问题讨论】:

  • 您可以将“标签”分配给选定的文本并为该标签定义颜色。示例:tkinter/tags
  • 无论您在哪里找到文本小部件的文档,都记录了这一切。搜索“标签”或“标签”。此外,该网站还有许多与在文本小部件中突出显示单词有关的问题。

标签: python python-3.x tkinter text-editor text-manipulation


【解决方案1】:

它使用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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 2014-03-12
    • 2013-09-30
    相关资源
    最近更新 更多