简体   繁体   中英

How to bold selected text in tkinter?

I had made a text editor in python where I am facing some problems. It has a bold button which enbolds whole text of the text editor, where I want to on apply it to selected text, but I cannot define the functionality properly.

Please help me to select the text and bold .

Here is my code:

#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, current_font_size, 'normal'))

bold_btn.configure(command=change_bold)

Change your function to:

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

To make the text normal again you should change the function to this:

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.first","sel.last")
    else:
        textwidget.tag_add("boldtext","sel.first","sel.last")
    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM