Set to bold the selected text using tags

前端 未结 2 1059
梦毁少年i
梦毁少年i 2021-01-06 07:30

I have been working trying to make a simple text editor, and have been experimenting with tags. I have been able to create justifying using tags. Now I\'m adding a bold opti

2条回答
  •  梦毁少年i
    2021-01-06 08:00

    You would only need tag_add() inside of your function:

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

    I just happened across a rather educational example by none other than Bryan Oakley,
    on a completely unrelated search!

    Here is a quick example of the more dynamic alternative:

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

提交回复
热议问题