在文本框Tkin中查找并更改单词的颜色

2024-05-16 06:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python制作一个开发环境类型的程序,并且有一个基本的工作程序,但是我有一个问题。我想用不同的颜色来突出某些单词,比如import,就像大多数开发环境一样,但是它不起作用!在

from tkinter import filedialog
from gameplay import *
from tkinter import *
import msvcrt as m
import os

openfileloc = ""

def combine_funcs(*funcs):
    def combined_func(*args, **kwargs):
        for f in funcs:
            f(*args, **kwargs)
    return combined_func

def load_file():
    rootFd = Tk()
    rootFd.withdraw()
    file_path = filedialog.askopenfilename()
    data = open(file_path, "r").read()
    txtFd.delete('1.0', END)
    txtFd.insert('1.0', data)
    openfile = data
    openfileloc = file_path

def save_file_dialog():
    rootFd = Tk()
    rootFd.withdraw()
    wr = filedialog.asksaveasfile(mode='w', defaultextension=".br")
    if wr.name != '':
        wr.write(txtFd.get('1.0', "end"))
        openfileloc = wr.name
    wr.close()
def save_file():
    if os.path.isfile(openfileloc):
        os.remove(file_path)
        wr = open(openfileloc, "w").write(txtFd.get('1.0', "end"))
    else:
        save_file_dialog()

def new_file():
    txtFd.delete('1.0', END)
    openfile = ""
    openfileloc = ""
# HEY STACKOVERFLOW PROBLEM IS HERE
def highlightKeywords():
    text = txtFd,get('1.0', 'end')
    KeywordSet1 = ['import', 'if'] # Hilighted in Yellow
    for i in range(len(text)):
        if KeywordSet[i] in text:
            txtFd.highlight_pattern(KeywordSet1[i], "yellow")

root = Tk()
root.title("GameBox Engine Editior - 0.0a")
menubar = Menu(root)
#Menu
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=new_file)
filemenu.add_command(label="Open", command=load_file)
filemenu.add_command(label="Save", command=save_file)
filemenu.add_command(label="Save as...", command=save_file_dialog)

filemenu.add_separator()

filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)

root.config(menu=menubar)
txtFd = Text(root)
txtFd.pack()

root.mainloop()

# THIS IS WHERE I CALL THE FUNCTION
running = True
while(running):
    m.getch()
    highlightKeywords()

没有错误,只是不起作用。你能帮助我吗?在


Tags: pathinimportaddsavedefrootwr