tkinter库textArea.tag_config不生效

选中文本的属性未改变

img


from tkinter import *
from tkinter.filedialog import *
from tkinter.ttk import *
import os


def openFile():
    filePath = askopenfilename()
    fileName = os.path.basename(filePath)
    tab = Frame(master=tabBar)
    tabBar.add(tab, text=fileName)
    textContains = Labelframe(master=tab)
    textContains.pack(expand=YES, fill=BOTH)
    global textArea
    textArea = Text(master=textContains)
    textArea.pack(side=LEFT, expand=YES, fill=BOTH)

    f = open(filePath, 'r', encoding='utf8')
    while True:
        data = f.readline()
        if not data:
            break
        else:
            textArea.insert(INSERT, data)
    f.close()
    scrollBar = Scrollbar(master=textContains)
    scrollBar.pack(fill=Y, side=RIGHT)
    scrollBar.config(command=textArea.yview)
    textArea.config(yscrollcommand=scrollBar.set)
    textArea.bind(sequence='', func=createTag)


def createTag(event):
    textArea.tag_add('here', SEL_FIRST, SEL_LAST)


def textEdit(event):
    textArea.tag_config('here', font=('blod', 30), foreground='red')


root = Tk()
root.title('myword v3.0.1')
root.state('zoomed')
menuBar = Menu(master=root)
root.configure(menu=menuBar)
fileMenu = Menu(master=menuBar, tearoff=0)
editMenu = Menu(master=menuBar, tearoff=0)
menuBar.add_cascade(label='file', menu=fileMenu)
menuBar.add_cascade(label='edit', menu=editMenu)
fileMenu.add_command(label='new')
fileMenu.add_command(label='open', command=openFile)
fileMenu.add_command(label='save')

editMenu.add_command(label='copy')
editMenu.add_command(label='paste')
editMenu.add_command(label='remark')
blodBt = Button(master=root, text='B', command=textEdit)
blodBt.pack(anchor=NW)

tabBar = Notebook(master=root)
tabBar.pack(expand=YES, fill=BOTH)

root.mainloop()

应该是这样的

img

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 你可以参考下这个问题的回答, 看看是否对你有帮助, 链接: https://ask.csdn.net/questions/657106
  • 我还给你找了一篇非常好的博客,你可以看看是否有帮助,链接:小程序textarea穿透、不跟随页面滚动解决方案
  • 除此之外, 这篇博客: tkinter模块中的 text控件 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:

    ##由于text只支持少数几种图像格式(gif,bmp等),不支持jpg,png格式##

    from PIL import Image,ImageTk
    #装载pic.png
    pic=Image.open("pic.png")
    photos=ImageTk.PhotoImage(pic)
    #在text控件的结尾插入图像
    text.image_create(tkinter.END,image=photos)
    #进行字体,字号等设置 ,需要big引用
    text.tag_configure("big",font("Arial",25,"bold"))
    #在text控件结尾插入文本,并使用big指定的字体属性
    text.insert(tkinter.END,"mzy","big")
    

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^