2016-03-11 49 views
-1

我正在用python製作一個開發環境類型的程序,並且有一個基本的工作程序,但我遇到了問題。我想強調某些單詞,如不同顏色的導入,就像大多數開發環境一樣,但它不會工作!在文本框中查找並更改單詞的顏色Tkinter

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

沒有錯誤,它只是不起作用。你可以幫我嗎?

+1

你有一個逗號,而不是當你定義的文本點。 它有效的原因是因爲你定義了一個元組。 –

+1

調用'mainloop'後的函數在窗口被銷燬之前不會執行。此外,文本小部件沒有'highlight_pattern'方法。 –

+0

你應該將你的函數綁定到文本小部件上以便按下按鍵。 –

回答

1

使用(從http://effbot.org/tkinterbook/text.htm

text.tag_configure('color', foreground='blue') 
text.insert(END, "This is blue\n", 'color') 

## you can also use relative position 
text.tag_add('color', "1.0", "1.4")