Python模块问题

时间:2011-05-17 13:50:28

标签: python module tkinter

我有两个名为“notepad.py”的.py文件& “pycolour.py”。首先是在父文件夹中,第二个是在“subdir”文件夹中。 第一个档案:

#notepad.py
from Tkinter import *
from subdir import pycolour

class SimpleNotepad(object):

    def __init__(self):
        self.frame = Frame(root, bg='#707070', bd=1)
        self.text_field = Text(self.frame, font='Verdana 10', bd=3, wrap='word')
        self.text_field.focus_set()
        self.btn = Button(root, text='try to colour', command=self.try_to_colour)

        self.coloured = pycolour.PyColour(root)

        self.frame.pack(expand=True, fill='both')
        self.text_field.pack(expand=True, fill='both')
        self.btn.pack()

    def try_to_colour(self):
        txt = self.text_field.get(1.0, 'end')
        text = str(txt).split('\n')
        for i in range(len(text)-1):
            self.coloured.colourize(i+1, len(text[i]))

root = Tk()
app = SimpleNotepad()
root.mainloop()

第二档:

#pycolour.py
from Tkinter import *
import keyword

#colorizing the Python code
class PyColour(Text):

    def __init__(self, parent):
        Text.__init__(self, parent)
        self.focus_set()
        self.tag_conf()

        self.bind('<Key>', self.key_pressed)

    tags = {'com' : '#009999',   #comment is darkgreen
            'str' : '#F50000',   #string is red
            'kw'  : '#F57A00',   #keyword is orange
            'obj' : '#7A00F5',   #function or class name is purple
            'int' : '#3333FF'    #integers is darkblue
            }

    def tag_conf(self):
        for tag, value in self.tags.items():
            self.tag_configure(tag, foreground=value)

    def tag_delete(self, start, end):
        for tag in self.tags.items():
            self.tag_remove(tag, start, end)

    def key_pressed(self, key):
        if key.char in ' :[(]),"\'':
            self.edit_separator() #for undo/redo

        cline = self.index(INSERT).split('.')[0]
        lastcol = 0
        char = self.get('%s.%d'%(cline, lastcol))
        while char != '\n':
            lastcol += 1
            char = self.get('%s.%d'%(cline, lastcol))

        self.colourize(cline,lastcol)

    def colourize(self, cline, lastcol):
        buffer = self.get('%s.%d'%(cline,0),'%s.%d'%(cline,lastcol))
        tokenized = buffer.split(' ')

        self.tag_remove('%s.%d'%(cline, 0), '%s.%d'%(cline, lastcol))

        quotes = 0
        start = 0
        for i in range(len(buffer)):
            if buffer[i] in ['"',"'"]:
                if quotes:
                   self.tag_add('str', '%s.%d'%(cline, start), '%s.%d'%(cline, i+1))
                   quotes = 0
                else:
                    start = i
                    quotes = 1
            elif buffer[i] == '#':
                self.tag_add('com', '%s.%d'%(cline, i), '%s.%d'%(cline, len(buffer)))
                break

        start, end = 0, 0
        obj_flag = 0
        for token in tokenized:
            end = start + len(token)+1
            if obj_flag:
                self.tag_add('obj', '%s.%d'%(cline, start), '%s.%d'%(cline, end))
                obj_flag = 0
            if token.strip() in keyword.kwlist:
                self.tag_add('kw', '%s.%d'%(cline, start), '%s.%d'%(cline, end))
                if token.strip() in ['def','class']: obj_flag = 1
            else:
                for index in range(len(token)):
                    try: int(token[index])
                    except ValueError: pass
                    else: self.tag_add('int', '%s.%d'%(cline, start+index))
            start += len(token)+1

if __name__ == '__main__':
    root = Tk()
    st = PyColour(root)
    st.pack(fill='both', expand='yes')
    root.mainloop()

“pycolour.py”为它自己的文本小部件中的python语法着色。我想在“notepad.py”中将名为“text_field”的文本小部件中的python语法着色,所以我编写了try_to_colour函数。问题是我不明白为什么这个功能不能正常工作。

2 个答案:

答案 0 :(得分:1)

PyColour是一个类。为了利用它的功能,你必须创建它的实例(例如self.text_field = PyColour(...))或者创建你自己的类,它是PyColour类的子类(例如class MyPyColour(PyColour): ...; self.text_field = MyPyColour(...)

答案 1 :(得分:0)

PyColour不是实用程序类,而是Text窗口小部件。它只能自己着色。所以你需要做的就是替换

self.text_field = Text(self.frame, ....)

self.text_field = PyColor(self.frame)
# find a different way to set font, etc.

问题在于PyColor调用self.tag_add()以及colourize()中的类似方法。这些只适用于PyColor实例self,而不适用于您的小部件。