如何在tkinter中加粗所选文本?

问题描述

我在python中制作了一个文本编辑器,遇到了一些问题。它具有一个 bold 按钮,该按钮将文本编辑器的整个文本括起来,我想在其中将其应用于所选文本,但是我无法正确定义功能

请帮助我选择文本和粗体

这是我的代码

#bold
bold_icon = tk.PhotoImage(file='C:\\Users\\soham\\OneDrive\\Desktop\\TEXT_EDITOR\\ICONS\\icons2\\bold.png')
bold_btn = ttk.Button(tool_bar,image= bold_icon)
bold_btn.grid(row=0,column=2,padx=5)

def change_bold():
    text_property=tk.font.Font(font=text_editor['font'])    
    if text_property.actual()['weight'] =='normal':
        text_editor.configure(font=(current_font_family,current_font_size,'bold'))
    if text_property.actual()['weight'] == 'bold':
        text_editor.configure(font=(current_font_family,'normal'))

bold_btn.configure(command=change_bold)

解决方法

将功能更改为:

def change_bold():
    textwidget.tag_configure("boldtext",font=textwidget.cget("font")+" bold")
    textwidget.tag_add("boldtext","sel.first","sel.last")

要使文本再次正常显示,您应该将功能更改为此:

textwidget.tag_configure("boldtext",font=textwidget.cget("font")+" bold")
def change_bold():
    if "boldtext" in textwidget.tag_names("sel.first"):
        textwidget.tag_remove("boldtext","sel.last")
    else:
        textwidget.tag_add("boldtext","sel.last")
    

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...