Beispiel #1
0
    def effect_on_text(self, tag_name=None, value=None):
        p = Percolator(self.text)
        if tag_name and value:
            self.__set_idlelib_tag_defs(tag_name, value)
        p.insertfilter(self.color_delegator)

        self.__add_common_event()
class HighlightTextBox(Text):
    '''Implements a Text box with a syntax highlighter'''
    def __init__(self, root, *args, **kwargs):
        Text.__init__(self, root, *args, **kwargs)
        self.d = ColorDelegator()
        self.p = Percolator(self)
        self.p.insertfilter(self.d)
Beispiel #3
0
    def __init__(self, *args, **kwargs):
        super(ConsoleText, self).__init__(*args, **kwargs)
        # The shared queue of the PRODUCER-CONSUMER model.
        self.__queue    = Queue.Queue()
        self.text.tag_configure('STDOUT',   foreground='black')
        self.text.tag_configure('STDERR',   foreground='red')
        self.text.tag_configure('TIP', foreground='forestgreen')
        self.text.tag_configure('HISTORY',   foreground='purple')
        self.text.tag_configure('RETVAL',    foreground='orange')
        
        self.text.bind('<KeyPress>', self.onKeyPress)

        
        # Experimenting with idlelib.AutoComplete
        #############################################################
        self.indentwidth    = 4
        self.tabwidth       = 4
        self.context_use_ps1    = '>>> '
        self.__autoComplete = AutoComplete(self)  
        #############################################################
                
        # Syntax highlight is implemented by idlelib
        #############################################################                
        self.percolator = Percolator(self.text)
        self.colorDelegator = ColorDelegator()
        self.percolator.insertfilter(self.colorDelegator)   
        #############################################################                        
        self.promptSymbol = '>>> '    
Beispiel #4
0
class TicText(Text):
    def __init__(self, parent, spell=None, **kw):
        Text.__init__(self, parent, wrap="word",
                      font="Times 14", takefocus=True, **kw)
        self.tg_regexp = re.compile("<[^>]*>")
        self.bind("<Control-c>", self.copy)
        self.bind("<Control-x>", self.cut)
        self.bind("<Return>", self.newline)
        self.tag_configure("h1", font="Times 16 bold", relief="raised")
        self.tag_configure("highlight", background="yellow", relief="raised")
        self.tag_configure("html_tag", foreground="blue")
        if spell:
            r, self.wd = pipe()
            self.rd, w = pipe()
            args = spell.split()
            self.sp = Popen(args, stdin=r, stdout=w)

            self.tag_configure("misspelled", foreground="red", underline=True)
            self.bind("<space>", self.Spellcheck)
        self.percolator = Percolator(self)
        self.percolator.insertfilter(HtmlColorDelegator())

    def copy(self, event=None):
        self.clipboard_clear()
        text = self.get("sel.first", "sel.last")
        self.clipboard_append(text)

    def cut(self, event):
        self.copy()
        self.delete("sel.first", "sel.last")

    def Spellcheck(self, event):
        """Spellcheck the word preceeding the insertion point"""
        index = self.search(r"\s", "insert", backwards=True, regexp=True)
        if index == "":
            index = "1.0"
        else:
            index = self.index("%s+1c" % index)
        word = self.get(index, "insert")
        write(self.wd, (word + "\n").encode())
        sleep(.01)
        spell = read(self.rd, 0x0fffffff)
        rm = len([None for i in spell.splitlines()
                  if i[:1] == b"#"])
        if not rm:
            self.tag_remove("misspelled", index, "%s+%dc" % (index, len(word)))
        else:
            self.tag_add("misspelled", index, "%s+%dc" % (index, len(word)))

    def highlight(self, regexp):
        text = self.get("1.0", "end")
        for m in re.finditer(regexp, text, re.I):
            self.tag_add("highlight", "1.0+%dc" % m.start(),
                         "1.0+%dc" % m.end())

    def newline(self, evt):
        self.insert("insert", "<br/>")
Beispiel #5
0
def main():
    from idlelib.Percolator import Percolator
    root = Tk()
    root.wm_protocol("WM_DELETE_WINDOW", root.quit)
    text = Text(background="white")
    text.pack(expand=1, fill="both")
    text.focus_set()
    p = Percolator(text)
    d = ColorDelegator()
    p.insertfilter(d)
    root.mainloop()
def main():
    from idlelib.Percolator import Percolator
    root = Tk()
    root.wm_protocol('WM_DELETE_WINDOW', root.quit)
    text = Text()
    text.pack()
    text.focus_set()
    p = Percolator(text)
    d = UndoDelegator()
    p.insertfilter(d)
    root.mainloop()
def main():
    from idlelib.Percolator import Percolator
    root = Tk()
    root.wm_protocol('WM_DELETE_WINDOW', root.quit)
    text = Text()
    text.pack()
    text.focus_set()
    p = Percolator(text)
    d = UndoDelegator()
    p.insertfilter(d)
    root.mainloop()
def _color_delegator(parent):
    from idlelib.Percolator import Percolator
    root = Tk()
    root.title("Test ColorDelegator")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    root.geometry("+%d+%d"%(x, y + 150))
    source = "if somename: x = 'abc' # comment\nprint"
    text = Text(root, background="white")
    text.insert("insert", source)
    text.pack(expand=1, fill="both")
    p = Percolator(text)
    d = ColorDelegator()
    p.insertfilter(d)
    root.mainloop()
Beispiel #9
0
def _color_delegator(parent):
    from idlelib.Percolator import Percolator
    root = Tk()
    root.title("Test ColorDelegator")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    root.geometry("+%d+%d" % (x, y + 150))
    source = "if somename: x = 'abc' # comment\nprint"
    text = Text(root, background="white")
    text.insert("insert", source)
    text.pack(expand=1, fill="both")
    p = Percolator(text)
    d = ColorDelegator()
    p.insertfilter(d)
    root.mainloop()
Beispiel #10
0
    def __init__(self, *args, **kwargs):
        super(ConsoleText, self).__init__(*args, **kwargs)
        # The shared queue of the PRODUCER-CONSUMER model.
        self.__queue    = Queue.Queue()
        self.text['wrap']   = 'word'
        self.text.tag_configure('STDOUT',   foreground='black')
        self.text.tag_configure('STDERR',   foreground='red')
        self.text.tag_configure('TIP', foreground='forestgreen')
        self.text.tag_configure('HISTORY',   foreground='purple')
        self.text.tag_configure('RETVAL',    foreground='orange')
        
        self.text.bind('<KeyPress>', self.on_key_press)

        
        # Experimenting with idlelib.AutoComplete
        #############################################################
        self.indent_width    = 4
        self.tab_width       = 4
        self.context_use_ps1    = '>>> '
        self.__auto_complete = AutoComplete(self)  
        #############################################################
                
        # Syntax highlight is implemented by idlelib
        #############################################################                
        self.percolator = Percolator(self.text)
        self.color_delegator = ColorDelegator()
        self.percolator.insertfilter(self.color_delegator)   
        #############################################################                        
        self.prompt_symbol = '>>> '    
Beispiel #11
0
    def setup_gui(self):
        self.root = root = tk.Tk()

        main_pane = tk.PanedWindow(root, orient=tk.HORIZONTAL, showhandle=True)
        main_pane.pack(fill=tk.BOTH, expand=True)
        left_frame = tk.Frame(main_pane)
        main_pane.add(left_frame)
        left_frame.grid_columnconfigure(0, weight=1)
        left_frame.grid_rowconfigure(0, weight=1)
        left_frame.grid_rowconfigure(1, weight=1)
        left_frame.grid_rowconfigure(2, weight=0)
        self.text = text = tk.Text(left_frame)
        text.grid(row=0, column=0, sticky=tk.N + tk.S + tk.E + tk.W)
        for l in self.source:
            text.insert(tk.END, '  ')
            text.insert(tk.END, l)
        text.config(state=tk.DISABLED)
        Percolator(self.text).insertfilter(ColorDelegator())
        self.canvas = canvas = tk.Canvas(main_pane, bg='white')
        main_pane.add(canvas)

        stdout_text = tk.Text(left_frame)
        stdout_text.grid(row=1, column=0, sticky=tk.N + tk.S + tk.E + tk.W)
        stdout_text.config(state=tk.DISABLED)
        sys.stdout = TkTextStream(stdout_text)
        button = tk.Button(left_frame, text="Step", command=root.quit)
        button.grid(row=2, column=0)
        root.bind("<KeyPress>", self._keydown)
        self.image = None
        self.last_line = None
Beispiel #12
0
    def __init__(我, tx= None):

        file_mp3= '_gtts_tc_yinyang.mp3'
        if sys.platform=='darwin':
            file_mp3= '_gtts_tc_yinyang.ogg' # mac 上 pygame 不吃 .mp3,只吃.ogg
        
        L= 55560 # time length of mp3, in ms
        sumT= sum([x[2] for x in timeText])
        
        if tx==None:
            tx= Text()
            tx.pack()
            Percolator(tx).insertfilter(ColorDelegator())
        
        tx.tag_configure('highlight', background='yellow')#, relief='raised')
                
        accT= 0
        Z=[]
        for x in timeText:
            z= [x[0], x[2], accT, accT+x[2], '1.0', '1.0'] 
            # 最後2個: z[4], z[5] , 預留給文字在螢幕上的位置 idx1, idx2
            accT += x[2]
            Z += [z]
        
        pygame.mixer.pre_init(frequency= 16000, channels=1, size=-16)
        pygame.mixer.init()
        pygame.mixer.music.load(file_mp3) #'_gtts_tc_yinyang.mp3')
        
        我.Z= Z
        我.L= L
        我.sumT= sumT
        我.tx= tx
Beispiel #13
0
 def makewidgets(self):
     sbar = Scrollbar(self)
     text = Text2(self, relief=SUNKEN)
     text.focus_set()
     p = Percolator(text)
     d = ColorDelegator()
     p.insertfilter(d)
     sbar.config(command=text.yview)
     text.config(yscrollcommand=sbar.set)
     sbar.pack(side=RIGHT, fill=Y)
     text.pack(side=LEFT, expand=YES, fill=BOTH)
     self.text = text
     self.copy = text.copy
     self.paste = text.paste
     self.delete = text.delete
     self.cut = text.cut
     self.highlight = text.higlight
Beispiel #14
0
def _color_delegator(parent):  # htest #
    from Tkinter import Toplevel, Text
    from idlelib.Percolator import Percolator

    top = Toplevel(parent)
    top.title("Test ColorDelegator")
    top.geometry("200x100+%d+%d" % (parent.winfo_rootx() + 200,
                  parent.winfo_rooty() + 150))
    source = "if somename: x = 'abc' # comment\nprint\n"
    text = Text(top, background="white")
    text.pack(expand=1, fill="both")
    text.insert("insert", source)
    text.focus_set()

    p = Percolator(text)
    d = ColorDelegator()
    p.insertfilter(d)
Beispiel #15
0
def _color_delegator(parent):  # htest #
    from Tkinter import Toplevel, Text
    from idlelib.Percolator import Percolator

    top = Toplevel(parent)
    top.title("Test ColorDelegator")
    top.geometry("200x100+%d+%d" % (parent.winfo_rootx() + 200,
                  parent.winfo_rooty() + 150))
    source = "if somename: x = 'abc' # comment\nprint\n"
    text = Text(top, background="white")
    text.pack(expand=1, fill="both")
    text.insert("insert", source)
    text.focus_set()

    p = Percolator(text)
    d = ColorDelegator('.py')
    p.insertfilter(d)
Beispiel #16
0
def _undo_delegator(parent):  # htest #
    import re
    import tkinter as tk
    from idlelib.Percolator import Percolator
    undowin = tk.Toplevel()
    undowin.title("Test UndoDelegator")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    undowin.geometry("+%d+%d" % (x, y + 150))

    text = Text(undowin, height=10)
    text.pack()
    text.focus_set()
    p = Percolator(text)
    d = UndoDelegator()
    p.insertfilter(d)

    undo = Button(undowin, text="Undo", command=lambda: d.undo_event(None))
    undo.pack(side='left')
    redo = Button(undowin, text="Redo", command=lambda: d.redo_event(None))
    redo.pack(side='left')
    dump = Button(undowin, text="Dump", command=lambda: d.dump_event(None))
    dump.pack(side='left')
def _undo_delegator(parent):  # htest #
    import re
    import tkinter as tk
    from idlelib.Percolator import Percolator
    undowin = tk.Toplevel()
    undowin.title("Test UndoDelegator")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    undowin.geometry("+%d+%d"%(x, y + 150))

    text = Text(undowin, height=10)
    text.pack()
    text.focus_set()
    p = Percolator(text)
    d = UndoDelegator()
    p.insertfilter(d)

    undo = Button(undowin, text="Undo", command=lambda:d.undo_event(None))
    undo.pack(side='left')
    redo = Button(undowin, text="Redo", command=lambda:d.redo_event(None))
    redo.pack(side='left')
    dump = Button(undowin, text="Dump", command=lambda:d.dump_event(None))
    dump.pack(side='left')
Beispiel #18
0
    def __init__(self,
                 parent,
                 language="Python",
                 font=("Courier", "10"),
                 numbersWidth=30,
                 *args,
                 **kwargs):
        '''Initialize CodePack instance'''
        tkinter.Frame.__init__(self, parent)

        self.text = ChangeText(self,
                               font=("Courier", 13),
                               wrap="word",
                               spacing3="2",
                               bd=0,
                               undo=True,
                               background="white",
                               *args,
                               **kwargs)
        self.text.pack(side=tkinter.RIGHT, expand=True, fill="both")
        self.text.bind("<<Change>>", self._changed)
        self.text.bind("<Control-KeyRelease-a>", self._highlightLine)

        self.lineNumbersFrame = tkinter.Frame(self)
        self.lineNumbersFrame.pack(side=tkinter.LEFT, fill="y")

        self.lineNumbers = tkinter.Canvas(self.lineNumbersFrame, width=30)
        self.lineNumbers.pack(expand=True, fill="y")

        self.font = font
        self.language = language

        self.p = Percolator(self.text)
        self.d = ColorDelegator(language=self.language, bg="white")
        self.p.insertfilter(self.d)

        self.text.tag_config("Current Line", background="cornsilk")
        self._setLanguageBindings()
Beispiel #19
0
def _undo_delegator(parent):
    from idlelib.Percolator import Percolator
    root = Tk()
    root.title("Test UndoDelegator")
    width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
    root.geometry("+%d+%d"%(x, y + 150))

    text = Text(root)
    text.config(height=10)
    text.pack()
    text.focus_set()
    p = Percolator(text)
    d = UndoDelegator()
    p.insertfilter(d)

    undo = Button(root, text="Undo", command=lambda:d.undo_event(None))
    undo.pack(side='left')
    redo = Button(root, text="Redo", command=lambda:d.redo_event(None))
    redo.pack(side='left')
    dump = Button(root, text="Dump", command=lambda:d.dump_event(None))
    dump.pack(side='left')

    root.mainloop()
Beispiel #20
0
    def create_linenumbers(self):
        """ Create the widget for displaying line numbers. """
        editwin = self.editwin
        text = self.text
        text_frame = editwin.text_frame
        self.textln = textln = Text(text_frame,
                                    width=self.width,
                                    height=1,
                                    wrap=NONE)

        # adjust font
        textln.config(
            font=(idleConf.GetOption('main', 'EditorWindow', 'font'),
                  idleConf.GetOption('main', 'EditorWindow', 'font-size')))

        textln.bind("<FocusIn>", self.focus_in_event)
        textln.bind('<Button-1>', self.button_ignore)
        textln.bind('<Button-2>', self.button_ignore)
        textln.bind('<Button-3>', self.button_ignore)
        textln.bind('<B1-Motion>', self.button_ignore)
        textln.bind('<B2-Motion>', self.button_ignore)
        textln.bind('<B3-Motion>', self.button_ignore)

        textln.bind("<Button-4>", self.button4)
        textln.bind("<Button-5>", self.button5)

        textln.tag_config('LINE', justify=RIGHT)
        textln.insert(END, '1')
        textln.tag_add('LINE', '1.0', END)

        # start the line numbers
        self.per = per = Percolator(textln)
        self.line_delegator = LineDelegator()
        per.insertfilter(self.line_delegator)
        textln._insert = self.line_delegator.delegate.insert
        textln._delete = self.line_delegator.delegate.delete

        lines = LineNumberDelegator(self)
        if _AFTER_UNDO:
            # Percolator.py's .insertfilter should have an "after=" argument
            lines.setdelegate(editwin.undo.delegate)
            editwin.undo.setdelegate(lines)
        else:
            editwin.per.insertfilter(lines)

        editwin.vbar['command'] = self.vbar_split
        editwin.text['yscrollcommand'] = self.yscroll_split
Beispiel #21
0
    def __init__(self, parent, spell=None, **kw):
        Text.__init__(self, parent, wrap="word",
                      font="Times 14", takefocus=True, **kw)
        self.tg_regexp = re.compile("<[^>]*>")
        self.bind("<Control-c>", self.copy)
        self.bind("<Control-x>", self.cut)
        self.bind("<Return>", self.newline)
        self.tag_configure("h1", font="Times 16 bold", relief="raised")
        self.tag_configure("highlight", background="yellow", relief="raised")
        self.tag_configure("html_tag", foreground="blue")
        if spell:
            r, self.wd = pipe()
            self.rd, w = pipe()
            args = spell.split()
            self.sp = Popen(args, stdin=r, stdout=w)

            self.tag_configure("misspelled", foreground="red", underline=True)
            self.bind("<space>", self.Spellcheck)
        self.percolator = Percolator(self)
        self.percolator.insertfilter(HtmlColorDelegator())
Beispiel #22
0
    def makeInputText(self, root):
        inputFm = Frame(root)
        self.inputText = Text(inputFm, height=10)
        inputScrollbar = Scrollbar(inputFm, orient=VERTICAL)
        self.inputText.pack(side="left", fill=BOTH, expand=YES)
        inputScrollbar.pack(side="left", fill=Y)
        self.inputText.config(yscrollcommand=inputScrollbar.set)
        inputScrollbar.config(command=self.inputText.yview)
        Percolator(self.inputText).insertfilter(ColorDelegator())
        self.inputText.bind('<Control-Shift-B>', self.runCmd)

        # 右键弹出式菜单
        popupCmd = [{
            "label": "执行命令",
            "cmd": self.runCmd
        }, {
            "label": "执行脚本",
            "cmd": self.runScript
        }]
        self.popup = Menu(root, tearoff=0)
        for item in popupCmd:
            self.popup.add_command(label=item["label"], command=item["cmd"])
        self.inputText.bind('<Button-3>', self.makePopupMenu)

        # 跟踪插入光标的行列信息
        self.inputText.bind('<KeyRelease>', self.updateInsertPos)
        self.inputText.bind('<ButtonRelease>', self.updateInsertPos)

        # 读取默认测试脚本
        if os.path.exists(os.getcwd() + "\\testsuite\default.py"):
            f = open(os.getcwd() + "\\testsuite\default.py")
            testsuite = f.read()
            f.close
            self.inputText.insert("1.0", testsuite)

        return inputFm
Beispiel #23
0
    def 建立文字區(self):
        """
        建立兩個Text區跟龜模組畫圖區並建立快捷鍵        
        """
        setup={}
        pane= PanedWindow(orient=HORIZONTAL, bg='black')
        text_frame= Frame(pane)
        self.text=text= Text(text_frame, name='text', padx=5,wrap='none', width=45,  bg='white', font= tuple(txtfont),tabs=('4c'),undo=True)
        text.name="text"
        vbar= Scrollbar(text_frame, name='vbar')
        
        vbar['command'] = text.yview
        vbar.pack(side=RIGHT, fill=Y)
        hbar = Scrollbar(text_frame, name='hbar', orient=HORIZONTAL)
        hbar['command'] = text.xview
        hbar.pack(side=BOTTOM, fill=X)
        
        text.pack(side=LEFT, fill=BOTH, expand=1)
 
        pane.add(text_frame)  
        
        
        text_frame2= Frame(pane)
        self.text2=text2= Text(text_frame2, name='text', padx=5,wrap='none', width=45, bg='white',font= tuple(txtfont),undo=True)
        text.name="text2"
        vbar= Scrollbar(text_frame2, name='vbar')
        vbar['command'] = text2.yview
        vbar.pack(side=RIGHT, fill=Y)
        hbar = Scrollbar(text_frame2, name='hbar', orient=HORIZONTAL)
        hbar['command'] = text2.xview
        hbar.pack(side=BOTTOM, fill=X)
        text2.pack(side=LEFT, fill=BOTH, expand=1)
        pane.add(text_frame2) 
        
        self.canvwidth= 800 
        self.canvheight= 600 
        turtle._Screen._root= self.root
        turtle._Screen._canvas= canvas= self._canvas= turtle.ScrolledCanvas(self.root, 800, 600, 1000, 800)
        canvas.adjustScrolls()
        canvas._rootwindow.bind('<Configure>', self.onResize)
        canvas._canvas['borderwidth'] = 0
        self.screen =screen = turtle.Screen()
        turtle.TurtleScreen.__init__(screen, screen._canvas)
        self.scanvas=scanvas= screen._canvas
        turtle.RawTurtle.screens = [screen]
        canvas.pack(side=LEFT, fill=BOTH, expand=1)
        pane.add(canvas) # for 畫圖
        # self.scanvas.bind('<Button-1>',self.焦點轉移)
        
        pane.pack(side=TOP, expand=1, fill=BOTH)
        
        Percolator(text).insertfilter(ColorDelegator())
        Percolator(text2).insertfilter(ColorDelegator())
        
        text.bind('<Control-MouseWheel>', self.滑鼠滾輪)
        text.bind('<Control-Button-4>', self.字體放大)
        text.bind('<Control-Button-5>', self.字體縮小)
        text2.bind('<Control-MouseWheel>', self.滑鼠滾輪)
        text2.bind('<Control-Button-4>', self.字體放大)
        text2.bind('<Control-Button-5>', self.字體縮小)
        text.bind('<Button-3>',self.選取標記)
        text2.bind('<Button-3>',self.選取標記)
        text.bind("<KeyRelease>", self.行號更新)
        text.bind("<ButtonRelease>", self.行號更新)
        text2.bind("<KeyRelease>", self.行號更新)
        text2.bind("<ButtonRelease>", self.行號更新)
Beispiel #24
0
 def __init__(self, root, *args, **kwargs):
     Text.__init__(self, root, *args, **kwargs)
     self.d = ColorDelegator()
     self.p = Percolator(self)
     self.p.insertfilter(self.d)
Beispiel #25
0
 def setUpClass(cls):
     cls.root = Tk()
     cls.text = Text(cls.root)
     cls.percolator = Percolator(cls.text)
Beispiel #26
0
class PercolatorTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.root = Tk()
        cls.text = Text(cls.root)

    @classmethod
    def tearDownClass(cls):
        del cls.text
        cls.root.destroy()
        del cls.root

    def setUp(self):
        self.percolator = Percolator(self.text)
        self.filter_one = MyFilter()
        self.filter_two = MyFilter()
        self.percolator.insertfilter(self.filter_one)
        self.percolator.insertfilter(self.filter_two)

    def tearDown(self):
        self.percolator.close()
        self.text.delete('1.0', END)

    def test_insertfilter(self):
        self.assertIsNotNone(self.filter_one.delegate)
        self.assertEqual(self.percolator.top, self.filter_two)
        self.assertEqual(self.filter_two.delegate, self.filter_one)
        self.assertEqual(self.filter_one.delegate, self.percolator.bottom)

    def test_removefilter(self):
        filter_three = MyFilter()
        self.percolator.removefilter(self.filter_two)
        self.assertEqual(self.percolator.top, self.filter_one)
        self.assertIsNone(self.filter_two.delegate)

        filter_three = MyFilter()
        self.percolator.insertfilter(self.filter_two)
        self.percolator.insertfilter(filter_three)
        self.percolator.removefilter(self.filter_one)
        self.assertEqual(self.percolator.top, filter_three)
        self.assertEqual(filter_three.delegate, self.filter_two)
        self.assertEqual(self.filter_two.delegate, self.percolator.bottom)
        self.assertIsNone(self.filter_one.delegate)

    def test_insert(self):
        self.text.insert('insert', 'foo')
        self.assertEqual(self.text.get('1.0', END), 'foo\n')
        self.assertTupleEqual(self.filter_one.insert_called_with,
                              ('insert', 'foo', None))

    def test_modify_insert(self):
        self.filter_one.insert = self.filter_one.uppercase_insert
        self.text.insert('insert', 'bAr')
        self.assertEqual(self.text.get('1.0', END), 'BAR\n')

    def test_modify_chain_insert(self):
        filter_three = MyFilter()
        self.percolator.insertfilter(filter_three)
        self.filter_two.insert = self.filter_two.uppercase_insert
        self.filter_one.insert = self.filter_one.lowercase_insert
        self.text.insert('insert', 'BaR')
        self.assertEqual(self.text.get('1.0', END), 'bar\n')

    def test_dont_insert(self):
        self.filter_one.insert = self.filter_one.dont_insert
        self.text.insert('insert', 'foo bar')
        self.assertEqual(self.text.get('1.0', END), '\n')
        self.filter_one.insert = self.filter_one.dont_insert
        self.text.insert('insert', 'foo bar')
        self.assertEqual(self.text.get('1.0', END), '\n')

    def test_without_filter(self):
        self.text.insert('insert', 'hello')
        self.assertEqual(self.text.get('1.0', 'end'), 'hello\n')

    def test_delete(self):
        self.text.insert('insert', 'foo')
        self.text.delete('1.0', '1.2')
        self.assertEqual(self.text.get('1.0', END), 'o\n')
        self.assertTupleEqual(self.filter_one.delete_called_with,
                              ('1.0', '1.2'))
Beispiel #27
0
    def __init__(self, filename=None):  #, root=None):
        self.root = root = turtle._root = Tk()
        root.wm_protocol("WM_DELETE_WINDOW", self._destroy)

        #################
        self.mBar = Frame(root, relief=RAISED, borderwidth=2)
        self.mBar.pack(fill=X)

        self.ExamplesBtn = self.makeLoadDemoMenu()
        self.OptionsBtn = self.makeHelpMenu()
        self.mBar.tk_menuBar(self.ExamplesBtn, self.OptionsBtn)  #, QuitBtn)

        root.title('Python turtle-graphics examples')
        #################
        self.left_frame = left_frame = Frame(root)
        self.text_frame = text_frame = Frame(left_frame)
        self.vbar = vbar = Scrollbar(text_frame, name='vbar')
        self.text = text = Text(text_frame,
                                name='text',
                                padx=5,
                                wrap='none',
                                width=45)
        vbar['command'] = text.yview
        vbar.pack(side=LEFT, fill=Y)
        #####################
        self.hbar = hbar = Scrollbar(text_frame,
                                     name='hbar',
                                     orient=HORIZONTAL)
        hbar['command'] = text.xview
        hbar.pack(side=BOTTOM, fill=X)
        #####################
        text['yscrollcommand'] = vbar.set
        text.config(font=txtfont)
        text.config(xscrollcommand=hbar.set)
        text.pack(side=LEFT, fill=Y, expand=1)
        #####################
        self.output_lbl = Label(left_frame,
                                height=1,
                                text=" --- ",
                                bg="#ddf",
                                font=("Arial", 16, 'normal'))
        self.output_lbl.pack(side=BOTTOM, expand=0, fill=X)
        #####################
        text_frame.pack(side=LEFT, fill=BOTH, expand=0)
        left_frame.pack(side=LEFT, fill=BOTH, expand=0)
        self.graph_frame = g_frame = Frame(root)

        turtle._Screen._root = g_frame
        turtle._Screen._canvas = turtle.ScrolledCanvas(g_frame, 800, 600, 1000,
                                                       800)
        #xturtle.Screen._canvas.pack(expand=1, fill="both")
        self.screen = _s_ = turtle.Screen()
        #####
        turtle.TurtleScreen.__init__(_s_, _s_._canvas)
        #####
        self.scanvas = _s_._canvas
        #xturtle.RawTurtle.canvases = [self.scanvas]
        turtle.RawTurtle.screens = [_s_]

        self.scanvas.pack(side=TOP, fill=BOTH, expand=1)

        self.btn_frame = btn_frame = Frame(g_frame, height=100)
        self.start_btn = Button(btn_frame,
                                text=" START ",
                                font=btnfont,
                                fg="white",
                                disabledforeground="#fed",
                                command=self.startDemo)
        self.start_btn.pack(side=LEFT, fill=X, expand=1)
        self.stop_btn = Button(btn_frame,
                               text=" STOP ",
                               font=btnfont,
                               fg="white",
                               disabledforeground="#fed",
                               command=self.stopIt)
        self.stop_btn.pack(side=LEFT, fill=X, expand=1)
        self.clear_btn = Button(btn_frame,
                                text=" CLEAR ",
                                font=btnfont,
                                fg="white",
                                disabledforeground="#fed",
                                command=self.clearCanvas)
        self.clear_btn.pack(side=LEFT, fill=X, expand=1)

        self.btn_frame.pack(side=TOP, fill=BOTH, expand=0)
        self.graph_frame.pack(side=TOP, fill=BOTH, expand=1)

        Percolator(text).insertfilter(ColorDelegator())
        self.dirty = False
        self.exitflag = False
        if filename:
            self.loadfile(filename)
        self.configGUI(NORMAL, DISABLED, DISABLED, DISABLED,
                       "Choose example from menu", "black")
        self.state = STARTUP
Beispiel #28
0
class CodePack(tkinter.Frame):
    lineText = None
    lastChar = ""
    indentNum = 0

    def __init__(self,
                 parent,
                 language="Python",
                 font=("Courier", "10"),
                 numbersWidth=30,
                 *args,
                 **kwargs):
        '''Initialize CodePack instance'''
        tkinter.Frame.__init__(self, parent)

        self.text = ChangeText(self,
                               font=("Courier", 13),
                               wrap="word",
                               spacing3="2",
                               bd=0,
                               undo=True,
                               background="white",
                               *args,
                               **kwargs)
        self.text.pack(side=tkinter.RIGHT, expand=True, fill="both")
        self.text.bind("<<Change>>", self._changed)
        self.text.bind("<Control-KeyRelease-a>", self._highlightLine)

        self.lineNumbersFrame = tkinter.Frame(self)
        self.lineNumbersFrame.pack(side=tkinter.LEFT, fill="y")

        self.lineNumbers = tkinter.Canvas(self.lineNumbersFrame, width=30)
        self.lineNumbers.pack(expand=True, fill="y")

        self.font = font
        self.language = language

        self.p = Percolator(self.text)
        self.d = ColorDelegator(language=self.language, bg="white")
        self.p.insertfilter(self.d)

        self.text.tag_config("Current Line", background="cornsilk")
        self._setLanguageBindings()

    def changeLanguage(self, language):
        self.language = language
        del (self.d, self.p)
        self.p = Percolator(self.text)
        self.d = ColorDelegator(language=self.language, bg="white")
        self.p.insertfilter(self.d)

    def _setLanguageBindings(self):
        '''Sets the Key Bindings based on the chosen language for text box'''
        lang = self.language

        #Overides Tabs for all languages and replaces with spaces
        def _overrideTab(event):
            if event.state == 4:
                pass
            else:
                self.text.insert(tkinter.INSERT, "    ")
                return "break"

        self.text.bind("<Tab>", _overrideTab)

        # Python (default) language bindings
        if lang == "Python":

            def _pythonReturn(event):
                self.lineText = self.text.get("insert -1l linestart",
                                              "insert -1l lineend")
                if self.lineText:
                    self.lastChar = self.lineText[-1]
                    self.indentNum = len(self.lineText) - len(
                        self.lineText.lstrip(' '))
                if self.lastChar == ":":
                    self.indentNum += 4
                self.text.insert("insert linestart", " " * self.indentNum)

            self.text.bind("<KeyRelease-Return>", _pythonReturn)

        # java lanaguage bindings
        elif lang == "Java":

            def _javaReturn(event):
                self.lineText = self.text.get("insert -1l linestart",
                                              "insert -1l lineend")
                if self.lineText:
                    self.lastChar = self.lineText[-1]
                    self.indentNum = len(self.lineText) - len(
                        self.lineText.lstrip(' '))
                if self.lastChar == "{":
                    self.indentNum += 4
                elif self.lastChar == "}":
                    if self.indentNum >= 4:
                        self.indentNum += -4
                elif self.lastChar.isalnum() or self.lastChar == ')':
                    self.text.insert("insert -1l lineend", ';')
                self.text.insert("insert linestart", " " * self.indentNum)

            self.text.bind("<KeyRelease-Return>", _javaReturn)

        #raise KeyError Exception if the language is not supported
        else:
            raise KeyError("Currently unsupported langauge")

    def _changed(self, event):
        '''events to process upon change of text box'''
        self.redrawLineNumbers()
        self._highlightLine()
        self.text.edit_separator()

    def redrawLineNumbers(self):
        '''redraw line numbers'''
        self.lineNumbers.delete("all")

        i = self.text.index("@0,0")
        while True:
            dline = self.text.dlineinfo(i)
            if dline is None: break
            y = dline[1]
            linenum = str(i).split(".")[0]
            self.lineNumbers.create_text(2, y, anchor="nw", text=linenum)
            i = self.text.index("%s+1line" % i)

    def _highlightLine(self, event=None):
        '''highlights the cursor's line in text widget'''
        self.text.tag_remove("Current Line", "1.0", tkinter.END)
        if self.text.tag_ranges("sel") == ():
            self.text.tag_add("Current Line", "insert linestart",
                              "insert lineend+1c")
        else:
            self.text.tag_add("Current Line", "insert linestart",
                              "insert lineend+1c")
            ranges = self.text.tag_ranges("sel")
            self.text.tag_remove("Current Line", ranges[0], ranges[1])
    def show(self, tag_filter=None):

        if self.hidden == False:
            self.hide()
            return

        self.hidden = False

        # add a text widget, left of code text widget
        self.text_frame = text_frame = Frame(self.editwin.text_frame)
        self.vbar = vbar = Scrollbar(text_frame, name='vbar')
        vbar.pack(side=RIGHT, fill=Y)

        theme = idleConf.GetOption('main', 'Theme', 'name')
        normal_colors = idleConf.GetHighlight(theme, 'normal')
        text_options = {
            'padx': 5,
            'wrap': 'none',
            'cursor': 'arrow',
            'wrap': 'none',
            'foreground': normal_colors['foreground'],
            'background': normal_colors['background'],
        }

        self.textln = textln = Text(text_frame, **text_options)
        textln.pack(side='left', fill=BOTH, expand=YES)
        vbar['command'] = textln.yview
        textln['yscrollcommand'] = vbar.set

        # adjust font

        textln.config(
            font=(idleConf.GetOption('main', 'EditorWindow', 'font'),
                  idleConf.GetOption('main', 'EditorWindow', 'font-size')))

        textln.bind("<ButtonRelease>", self.focus_in_event)
        textln.bind("<Return>", self.enter_callback)
        textln.bind("<Escape>", self.escape_callback)
        textln.bind('<FocusOut>', self.focus_out, '+')

        # pass through keybindings for classdefbrowser
        keydefs = idleConf.GetExtensionBindings('CodeBrowser')
        for event, keylist in list(keydefs.items()):
            for k in keylist:

                def passthru(event, evName=event, text=self.text):
                    text.event_generate(evName)

                try:
                    textln.bind(k, passthru)
                except TclError as err:
                    print(err)
                    pass

        # start the line numbers
        self.per = per = Percolator(textln)
        self.color = ColorDelegator()

        self.per.insertfilter(self.color)

        self.line_delegator = LineDelegator()
        per.insertfilter(self.line_delegator)
        textln._insert = self.line_delegator.delegate.insert
        textln._delete = self.line_delegator.delegate.delete

        self.update_display(tag_filter)
        self.textfont = ""
        self.font_timer_event()

        self.nearest()

        text_frame.place(x=0, rely=1, relheight=1, relwidth=1, anchor=SW)
        text_frame.lift()
Beispiel #30
0
 def add_colors_to_text(text):
     color_config(text)
     p = Percolator(text)
     d = ColorDelegator()
     p.insertfilter(d)
Beispiel #31
0
    def __init__(我, filename=None):
        我.root = root = turtle._root = Tk()

        root.title(
            'Python 傳統漢字 (Traditional Chinese, tc) 龜作圖 (turtle-graphics) 範例集 (examples)'
        )

        root.wm_protocol("WM_DELETE_WINDOW", 我._destroy)

        if darwin:
            import subprocess
            # Make sure we are the currently activated OS X application
            # so that our menu bar appears.
            p = subprocess.Popen(
                [
                    'osascript',
                    '-e',
                    'tell application "System Events"',
                    '-e',
                    'set frontmost of the first process whose '
                    'unix id is {} to true'.format(os.getpid()),
                    '-e',
                    'end tell',
                ],
                stderr=subprocess.DEVNULL,
                stdout=subprocess.DEVNULL,
            )

        root.grid_rowconfigure(0, weight=1)
        root.grid_columnconfigure(0, weight=1)
        root.grid_columnconfigure(1, minsize=90, weight=1)
        root.grid_columnconfigure(2, minsize=90, weight=1)
        root.grid_columnconfigure(3, minsize=90, weight=1)

        我.mBar = Menu(root, relief=RAISED, borderwidth=2)
        我.mBar.add_cascade(menu=我.makeLoadDemoMenu(我.mBar),
                           label='範例',
                           underline=0)
        我.mBar.add_cascade(menu=我.makeFontMenu(我.mBar),
                           label='字體',
                           underline=0)
        我.mBar.add_cascade(menu=我.makeHelpMenu(我.mBar),
                           label='求助',
                           underline=0)

        我.mBar.add_cascade(menu=我.make翻譯Menu(我.mBar), label='翻譯',
                           underline=0)  # (1)

        root['menu'] = 我.mBar

        pane = PanedWindow(orient=HORIZONTAL,
                           sashwidth=5,
                           sashrelief=SOLID,
                           bg='#ddd')
        pane.add(我.makeTextFrame(pane))
        pane.add(我.makeGraphFrame(pane))

        pane.grid(row=0, columnspan=5, sticky='news')

        我.output_lbl = Label(root,
                             height=1,
                             text=" --- ",
                             bg="#ddf",
                             font=("Arial", 16, 'normal'),
                             borderwidth=2,
                             relief=RIDGE)

        我.翻譯_btn = Button(root,
                          text=" 翻譯 ",
                          font=btnfont,
                          fg="blue",
                          disabledforeground="#fed",
                          command=我.翻譯檔案)

        我.start_btn = Button(root,
                             text=" 開始 ",
                             font=btnfont,
                             fg="white",
                             disabledforeground="#fed",
                             command=我.startDemo)

        我.stop_btn = Button(root,
                            text=" 停止 ",
                            font=btnfont,
                            fg="white",
                            disabledforeground="#fed",
                            command=我.stopIt)

        我.clear_btn = Button(root,
                             text=" 清除 ",
                             font=btnfont,
                             fg="white",
                             disabledforeground="#fed",
                             command=我.clearCanvas)

        我.output_lbl.grid(row=1, column=0, sticky='news', padx=(0, 5))

        我.翻譯_btn.grid(row=1, column=1, sticky='ew')

        我.start_btn.grid(row=1, column=2, sticky='ew')
        我.stop_btn.grid(row=1, column=3, sticky='ew')
        我.clear_btn.grid(row=1, column=4, sticky='ew')

        Percolator(我.text).insertfilter(ColorDelegator())
        我.dirty = False
        我.exitflag = False
        if filename:
            我.loadfile(filename)
        我.configGUI(DISABLED, DISABLED, DISABLED, "由選單 選 範例", "black")
        我.state = STARTUP
class PercolatorTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.root = Tk()
        cls.text = Text(cls.root)

    @classmethod
    def tearDownClass(cls):
        cls.text.destroy()
        cls.root.destroy()
        del cls.text, cls.root

    def setUp(self):
        self.percolator = Percolator(self.text)
        self.filter_one = MyFilter()
        self.filter_two = MyFilter()
        self.percolator.insertfilter(self.filter_one)
        self.percolator.insertfilter(self.filter_two)

    def tearDown(self):
        self.percolator.close()
        self.text.delete('1.0', END)

    def test_insertfilter(self):
        self.assertIsNotNone(self.filter_one.delegate)
        self.assertEqual(self.percolator.top, self.filter_two)
        self.assertEqual(self.filter_two.delegate, self.filter_one)
        self.assertEqual(self.filter_one.delegate, self.percolator.bottom)

    def test_removefilter(self):
        filter_three = MyFilter()
        self.percolator.removefilter(self.filter_two)
        self.assertEqual(self.percolator.top, self.filter_one)
        self.assertIsNone(self.filter_two.delegate)

        filter_three = MyFilter()
        self.percolator.insertfilter(self.filter_two)
        self.percolator.insertfilter(filter_three)
        self.percolator.removefilter(self.filter_one)
        self.assertEqual(self.percolator.top, filter_three)
        self.assertEqual(filter_three.delegate, self.filter_two)
        self.assertEqual(self.filter_two.delegate, self.percolator.bottom)
        self.assertIsNone(self.filter_one.delegate)

    def test_insert(self):
        self.text.insert('insert', 'foo')
        self.assertEqual(self.text.get('1.0', END), 'foo\n')
        self.assertTupleEqual(self.filter_one.insert_called_with,
                              ('insert', 'foo', None))

    def test_modify_insert(self):
        self.filter_one.insert = self.filter_one.uppercase_insert
        self.text.insert('insert', 'bAr')
        self.assertEqual(self.text.get('1.0', END), 'BAR\n')

    def test_modify_chain_insert(self):
        filter_three = MyFilter()
        self.percolator.insertfilter(filter_three)
        self.filter_two.insert = self.filter_two.uppercase_insert
        self.filter_one.insert = self.filter_one.lowercase_insert
        self.text.insert('insert', 'BaR')
        self.assertEqual(self.text.get('1.0', END), 'bar\n')

    def test_dont_insert(self):
        self.filter_one.insert = self.filter_one.dont_insert
        self.text.insert('insert', 'foo bar')
        self.assertEqual(self.text.get('1.0', END), '\n')
        self.filter_one.insert = self.filter_one.dont_insert
        self.text.insert('insert', 'foo bar')
        self.assertEqual(self.text.get('1.0', END), '\n')

    def test_without_filter(self):
        self.text.insert('insert', 'hello')
        self.assertEqual(self.text.get('1.0', 'end'), 'hello\n')

    def test_delete(self):
        self.text.insert('insert', 'foo')
        self.text.delete('1.0', '1.2')
        self.assertEqual(self.text.get('1.0', END), 'o\n')
        self.assertTupleEqual(self.filter_one.delete_called_with,
                              ('1.0', '1.2'))
Beispiel #33
0
 def setUp(self):
     self.percolator = Percolator(self.text)
     self.filter_one = MyFilter()
     self.filter_two = MyFilter()
     self.percolator.insertfilter(self.filter_one)
     self.percolator.insertfilter(self.filter_two)
Beispiel #34
0
 def changeLanguage(self, language):
     self.language = language
     del (self.d, self.p)
     self.p = Percolator(self.text)
     self.d = ColorDelegator(language=self.language, bg="white")
     self.p.insertfilter(self.d)
Beispiel #35
0
    def __init__(self, filename=None):
        self.root = root = turtle._root = Tk()
        root.title('Python turtle-graphics examples')
        root.wm_protocol("WM_DELETE_WINDOW", self._destroy)

        if darwin:
            import subprocess
            # Make sure we are the currently activated OS X application
            # so that our menu bar appears.
            p = subprocess.Popen(
                [
                    'osascript',
                    '-e',
                    'tell application "System Events"',
                    '-e',
                    'set frontmost of the first process whose '
                    'unix id is {} to true'.format(os.getpid()),
                    '-e',
                    'end tell',
                ],
                stderr=subprocess.DEVNULL,
                stdout=subprocess.DEVNULL,
            )

        root.grid_rowconfigure(0, weight=1)
        root.grid_columnconfigure(0, weight=1)
        root.grid_columnconfigure(1, minsize=90, weight=1)
        root.grid_columnconfigure(2, minsize=90, weight=1)
        root.grid_columnconfigure(3, minsize=90, weight=1)

        self.mBar = Menu(root, relief=RAISED, borderwidth=2)
        self.mBar.add_cascade(menu=self.makeLoadDemoMenu(self.mBar),
                              label='Examples',
                              underline=0)
        self.mBar.add_cascade(menu=self.makeFontMenu(self.mBar),
                              label='Fontsize',
                              underline=0)
        self.mBar.add_cascade(menu=self.makeHelpMenu(self.mBar),
                              label='Help',
                              underline=0)
        root['menu'] = self.mBar

        pane = PanedWindow(orient=HORIZONTAL,
                           sashwidth=5,
                           sashrelief=SOLID,
                           bg='#ddd')
        pane.add(self.makeTextFrame(pane))
        pane.add(self.makeGraphFrame(pane))
        pane.grid(row=0, columnspan=4, sticky='news')

        self.output_lbl = Label(root,
                                height=1,
                                text=" --- ",
                                bg="#ddf",
                                font=("Arial", 16, 'normal'),
                                borderwidth=2,
                                relief=RIDGE)
        self.start_btn = Button(root,
                                text=" START ",
                                font=btnfont,
                                fg="white",
                                disabledforeground="#fed",
                                command=self.startDemo)
        self.stop_btn = Button(root,
                               text=" STOP ",
                               font=btnfont,
                               fg="white",
                               disabledforeground="#fed",
                               command=self.stopIt)
        self.clear_btn = Button(root,
                                text=" CLEAR ",
                                font=btnfont,
                                fg="white",
                                disabledforeground="#fed",
                                command=self.clearCanvas)
        self.output_lbl.grid(row=1, column=0, sticky='news', padx=(0, 5))
        self.start_btn.grid(row=1, column=1, sticky='ew')
        self.stop_btn.grid(row=1, column=2, sticky='ew')
        self.clear_btn.grid(row=1, column=3, sticky='ew')

        Percolator(self.text).insertfilter(ColorDelegator())
        self.dirty = False
        self.exitflag = False
        if filename:
            self.loadfile(filename)
        self.configGUI(DISABLED, DISABLED, DISABLED,
                       "Choose example from menu", "black")
        self.state = STARTUP
Beispiel #36
0
    def __init__(我, filename=None):

        #turtleOld._root=
        我.root = root = turtle._root = Tk()  #Toplevel() #Tk()

        root.title('傳統漢字 (Traditional Chinese, tc) 龜作圖 範例集')

        root.wm_protocol("WM_DELETE_WINDOW", 我._destroy)

        if darwin:
            import subprocess
            # Make sure we are the currently activated OS X application
            # so that our menu bar appears.
            p = subprocess.Popen(
                [
                    'osascript',
                    '-e',
                    'tell application "System Events"',
                    '-e',
                    'set frontmost of the first process whose '
                    'unix id is {} to true'.format(os.getpid()),
                    '-e',
                    'end tell',
                ],
                stderr=subprocess.DEVNULL,
                stdout=subprocess.DEVNULL,
            )

        root.grid_rowconfigure(0, weight=1)
        root.grid_columnconfigure(0, weight=1)
        root.grid_columnconfigure(1, weight=1, minsize=90)
        root.grid_columnconfigure(2, weight=1, minsize=90)
        root.grid_columnconfigure(3, weight=1, minsize=90)

        我.mBar = Menu(root, relief=RAISED, borderwidth=2)
        我.mBar.add_cascade(label='範例',
                           menu=我.makeLoadDemoMenu(我.mBar))  #, underline=0)
        我.mBar.add_cascade(label='字體',
                           menu=我.makeFontMenu(我.mBar))  #, underline=0)
        我.mBar.add_cascade(label='求助',
                           menu=我.makeHelpMenu(我.mBar))  #, underline=0)
        我.mBar.add_cascade(label='新功能',
                           menu=我.新功能選單(我.mBar))  #, underline=0) # (1)
        root['menu'] = 我.mBar

        pane = PanedWindow(
            orient=HORIZONTAL,
            bg='black')  #'#ddd') #sashwidth=6, #sashrelief=SOLID,
        pane.add(我.makeTextFrame(pane))  # for English program display
        pane.add(我.makeTextFrame2(pane))  # for 漢字程式 展示 及修改
        pane.add(我.makeGraphFrame(pane))  # for 畫圖

        pane.grid(row=0, columnspan=4, sticky='news')

        我.output_lbl = Label(root,
                             text="---",
                             font=btnfont,
                             bg="#ddf",
                             borderwidth=2,
                             relief=RIDGE)
        我.start_btn = Button(root,
                             text="開始",
                             command=我.startDemo,
                             font=btnfont,
                             fg="white",
                             disabledforeground="#fed")
        我.stop_btn = Button(root,
                            text="停止",
                            command=我.stopIt,
                            font=btnfont,
                            fg="white",
                            disabledforeground="#fed")
        我.clear_btn = Button(root,
                             text="清除",
                             command=我.clearCanvas,
                             font=btnfont,
                             fg="white",
                             disabledforeground="#fed")

        我.output_lbl.grid(row=1, column=0, sticky='news', padx=(0, 3))
        我.start_btn.grid(row=1, column=1, sticky='ew')
        我.stop_btn.grid(row=1, column=2, sticky='ew')
        我.clear_btn.grid(row=1, column=3, sticky='ew')

        # 讓 程式內文 有 語法 顏色,超酷的!
        Percolator(我.text).insertfilter(ColorDelegator())
        Percolator(我.text2).insertfilter(ColorDelegator())

        我.dirty = False
        我.exitflag = False

        if filename:
            我.loadfile(filename)

        我.configGUI(DISABLED, DISABLED, DISABLED, "由選單 選範例", "black")
        我.state = STARTUP

        # 在 桌面上 建一個 _tcDir 來存放翻譯的檔案。
        dektopDir = os.path.join(os.path.expanduser('~'), 'Desktop')
        我.tcDir = tcDir = os.path.join(dektopDir, '_tcDir')  ## 用底線代表用過可丟。
        if not os.path.exists(tcDir):
            os.mkdir(tcDir)
        if tcDir not in sys.path: sys.path += [tcDir]

        # 順便 把 turtle_tc.py 們 copy 過去,方便在裡面 修改 學習。
        import shutil
        for f in [
                'turtle_tc.py', 'turtle_tc_alias.py',
                'turtle_docstringdict_tc.py'
        ]:
            srcfile = os.path.join(os.path.dirname(__file__), f)
            tgtfile = os.path.join(tcDir, f)
            if not os.path.exists(tgtfile): shutil.copy(srcfile, tcDir)
Beispiel #37
0
def main00():

    Z=[] 
    # 這個 Z 存放音文同步資訊(進一步處理),
    # 將在 ryShowText 中設定,rySync01 中使用。
    
    file_mp3= '_gtts_tc_yinyang.mp3'
    L= 55560 # time length of mp3, in ms
    #
    # 這個 L 是 file_mp3 的 時間長度,還不知道如何自動找出來,
    # 目前是用 ryPlay() 先 播放一次,找到 lastPos 記錄下來得知。
    # 可能有點不準,自動方法要再研究。
    #
    
    sumT= sum([x[2] for x in timeText])
    #
    # 這個 timeText 來自 ryGoogleTTS.py,
    # 從那邊跑出結果,再貼進來這裡,
    # 半手動半自動做些字串處理
    #
    # sumT=  221472
    # print('sumT= ', sumT)
    #
    # 這個 sumT 是 從ryGoogleTTS.py 弄回來的 mp3 之檔案長度 (in bytes)
    #
    # 我覺得 L 與 sumT 應該有正比關係,經過1天的實驗,果然如此。
    #

    #
    # 學會 tkinter.Text 的 高亮 (highlight) 技巧,
    # 再配合 pygame.mixer.music 的播放聲音(mp3)
    # 於是音文同步就做出來了。
    #
    tx= Text()
    tx.pack()
    tx.tag_configure('highlight', background='yellow')#, relief='raised')
    #
    # 把 文字的第5列,從頭(0)到尾(end)加標籤,此處標籤意指高亮(底色變黃)
    # 方法如下2行
    #
    # tx.tag_add('highlight','5.0','5.end')
    # tx.tag_remove('highlight','5.0','5.end')
    #
    # 上述方法 參考這裡很多,http://www.tkdocs.com/tutorial/text.html
    #
    
    # 讓 程式內文 有 語法 顏色,超酷的!
    Percolator(tx).insertfilter(ColorDelegator())

    def ryMain():
    
        ryShowText()
        ryInit()
        #rySync01()
        #rySync02()
        rySync03()
        
        setButtons()
        
    def ryShowText():
        nonlocal Z

        tx.delete('1.0','end')
        
        accT= 0
        Z=[]
        for x in timeText:
            z= [x[0], x[2], accT, accT+x[2], '1.0', '1.0'] 
            # 最後2個: z[4], z[5] , 預留給文字在螢幕上的位置 idx1, idx2
            accT += x[2]
            Z += [z]
        
        ''' Z=[
            ('from', 3312, 0, 3312),
            ('turtle_tc', 8640, 3312, 11952),
            ('import', 3168, 11952, 15120),
            ('def', 3024, 15120, 18144),
            ('陰', 2880, 18144, 21024),
            ('半徑', 3456, 21024, 24480),
            ('顏色1', 5040, 24480, 29520),
            ('顏色2', 3888, 29520, 33408),
            ...
            ]
        '''
        
        '''
        for n,z in enumerate(Z):
        
            #text= '%s:%04d:%s:%d\n'%(idx,n,z[0],len(z[0]))#'%s'%(z[0])
            text= '%s\n'%(str(z))
            tx.insert('end','%s'%(text))
        '''
        
        text= tc_yinyang_py
        tx.insert('end',text)
            
    def ryHighLight():
        nonlocal Z
        tx.delete('1.0','end')
        
        Y= []

        for n,z in enumerate(Z):
        
            #text= '%s:%04d:%s:%d\n'%(idx,n,z[0],len(z[0]))#'%s'%(z[0])
            xxxx= '\n' if n%4==0 else '\t'
            text= '%s%s'%(z[0],xxxx)
            
            idx1= tx.index('insert')
            tx.insert('insert',text)            
            idx2= tx.index('insert')
            
            y= (text, idx1, idx2)
            
            Y += [y]
        
        #print(Y)
            
        for i,y in enumerate(Y):

            idx1= y[1]
            idx2= y[2]
            
            tx.tag_add('highlight',idx1,idx2)
            tx.see(idx1)
            tx.update()
            
            time.sleep(0.5)
            
            tx.tag_remove('highlight',idx1,idx2)
            tx.update()
            
    def ryInit():
        nonlocal file_mp3
        
        pygame.mixer.pre_init(frequency= 16000, channels=1, size=-16)
        pygame.mixer.init()
        pygame.mixer.music.load(file_mp3) #'_gtts_tc_yinyang.mp3')
    
    def ryPlay():
        pygame.mixer.music.play()
        pos=  pygame.mixer.music.get_pos()
        lastPos= pos
        while pos != -1:
            pos=  pygame.mixer.music.get_pos()
            if pos != -1: lastPos= pos
            if pos%1000==0:
                ryPos(pos)

        tx.delete('1.0','1.end')
        tx.insert('1.0','lastPos= %d'%int(lastPos))
        tx.update()

    def ryPos(pos=0):
        if pos!=0: pos=  pygame.mixer.music.get_pos()
        tx.delete('1.0','1.end')
        tx.insert('1.0','%d'%int(pos))
        tx.update()

    def rySync01(): # 這裡還有很多其他改的空間,故名稱加上 01
        nonlocal Z

        for n,z in enumerate(Z):
            idx='%d.0'%(n+1)
            
            #text= '%s:%04d:%s:%d\n'%(idx,n,z[0],len(z[0]))#'%s'%(z[0])
            text= '%s\n'%(z[0])
            
            tx.insert(idx,'%s'%(text))
            
        pygame.mixer.music.play()
        
        n=0
        tmpBool= True
        #busy= pygame.mixer.music.get_busy()
        pos=  pygame.mixer.music.get_pos()
        while pos!=-1:#busy: # pos 正常情形會傳回聲音的時間位置(ms),聲音結束時,pos==-1
            #busy= pygame.mixer.music.get_busy()
            pos=  pygame.mixer.music.get_pos() # in msec
            
            #print('pos= ',pos/L*sumT)

            iPos= int(pos/L*sumT) # 這就是我說的「正比關係」!!
            
            if n<len(Z):
                if iPos>=Z[n][2] and iPos<=Z[n][3] and tmpBool==True:

                    #print(Z[n][0], iPos)
                    
                    #tx.delete('1.0','1.end')
                    #tx.insert('1.0','%s'%(Z[n][0]))
                    
                    #
                    # 目前先採用「整行高亮」的方式,
                    # 隨後再改成依照文字排版的方式來高亮
                    #

                    if n>=1:
                        tx.tag_remove('highlight','%d.0'%(n),'%d.end'%(n))
                    tx.tag_add('highlight','%d.0'%(n+1),'%d.end'%(n+1))
                    tx.see('%d.0'%(n+1)) # 加這行,才能自動捲軸。
                    tx.update()
                    
                    tmpBool= False
                    
                elif iPos >= Z[n][3]:
                    n+=1
                    tmpBool= True

    def rySync02(): # 這裡還有很多其他改的空間,故名稱加上 02
        nonlocal Z

        tx.delete('1.0','end')
        
        #
        # 把文字依 「某種格式」 擺在 螢幕上,其位置存入 Z[4], Z[5]
        #
        # 參考:  Text widget indices
        # http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/text-index.html
        #
        # idx= 'line.column'
        #
        # tk.INSERT
        #   The position of the insertion cursor in the text widget. 
        #   This constant is equal to the string 'insert'.
        #
        
        #Y= []
        for n,z in enumerate(Z):
        
            #
            # 暫時假設文字格式為 每列 (line) 4 個 text
            #
            xxxx= '\n' if (n+1)%4==0 else '\t'
            text= '%s%s'%(z[0],xxxx)
            
            #
            # 一邊把文字插入 tx, 一邊記錄其在螢幕上的位置 idx1, idx2
            #
            idx1= tx.index('insert')
            tx.insert('insert',text)            
            idx2= tx.index('insert')
            
            #y= (idx1, idx2)
            #Z[n] += (idx1, idx2) # 這組 index 資訊就存入 Z[n][4], Z[n][5]
            Z[n][4], Z[n][5]= idx1, idx2
            
            #Y += [y]
        
        #print(Z)
        '''
        Z= [
            ('from', 3312, 0, 3312, '1.0', '1.5'), 
            ('turtle_tc', 8640, 3312, 11952, '1.5', '1.15'), 
            ('import', 3168, 11952, 15120, '1.15', '1.22'), 
            ('def', 3024, 15120, 18144, '1.22', '2.0'), 
            ('陰', 2880, 18144, 21024, '2.0', '2.2'), 
            ('半徑', 3456, 21024, 24480, '2.2', '2.5'), 
            ('顏色1', 5040, 24480, 29520, '2.5', '2.9'), 
            ('顏色2', 3888, 29520, 33408, '2.9', '3.0'),
            ...
            ]
        '''
        
        pygame.mixer.music.play()
        
        n=0
        tmpBool= True

        pos=  pygame.mixer.music.get_pos()
        while pos!=-1:

            pos=  pygame.mixer.music.get_pos() # in msec
            
            #print('pos= ',pos/L*sumT)

            # 重要音文同步計算公式
            iPos= int(pos/L*sumT) # 這就是我說的「正比關係」!!
            
            if n<len(Z):
                if iPos>=Z[n][2] and iPos<=Z[n][3] and tmpBool==True:

                    if n>=1:
                        tx.tag_remove('highlight',Z[n-1][4],Z[n-1][5])
                    tx.tag_add('highlight',Z[n][4],Z[n][5])
                    
                    tx.see(Z[n][5]) # 加這行,才能自動捲軸。
                    tx.update()     # 加這行,才能即時顯示效果。
                    
                    tmpBool= False
                    
                elif iPos >= Z[n][3]:
                    n+=1
                    tmpBool= True
 

    def rySync03(): # 這裡還有很多其他改的空間,故名稱加上 03
        nonlocal Z

        tx.delete('1.0','end')
        
        #
        # 把文字依 「某種格式」 擺在 螢幕上,其位置存入 Z[4], Z[5]
        #
        # 參考:  Text widget indices
        # http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/text-index.html
        #
        # idx= 'line.column'
        #
        # tk.INSERT
        #   The position of the insertion cursor in the text widget. 
        #   This constant is equal to the string 'insert'.
        #
        
        tcPy= tc_yinyang_py
        tx.insert('insert',tcPy)
        
        #Y= []
        idx2= '1.0'
        for n,z in enumerate(Z):
            '''
            #
            # 暫時假設文字格式為 每列 (line) 4 個 text
            #
            xxxx= '\n' if (n+1)%10==0 else '\t'
            text= '%s%s'%(z[0],xxxx)
            
            #
            # 一邊把文字插入 tx, 一邊記錄其在螢幕上的位置 idx1, idx2
            #
            idx1= tx.index('insert')
            tx.insert('insert',text)            
            idx2= tx.index('insert')
            '''
            
            #
            # 如何 根據 text= z[0] 在 tcPy 中 「循序」找到 idx1, idx2 
            #
            text= z[0]
            idx1= tx.search(text, idx2) # idx2= '1.0' for init
            idx2= idx1 + ' + %d chars'%len(text)
            idx2= tx.index(idx2)
            
            
            #y= (idx1, idx2)

            #Z[n] += (idx1, idx2) # 這組 index 資訊就存入 Z[n][4], Z[n][5]
            Z[n][4], Z[n][5]= idx1, idx2
            
            #Y += [y]
        
        #print(Z)
        '''
        Z= [
            ('from', 3312, 0, 3312, '1.0', '1.5'), 
            ('turtle_tc', 8640, 3312, 11952, '1.5', '1.15'), 
            ('import', 3168, 11952, 15120, '1.15', '1.22'), 
            ('def', 3024, 15120, 18144, '1.22', '2.0'), 
            ('陰', 2880, 18144, 21024, '2.0', '2.2'), 
            ('半徑', 3456, 21024, 24480, '2.2', '2.5'), 
            ('顏色1', 5040, 24480, 29520, '2.5', '2.9'), 
            ('顏色2', 3888, 29520, 33408, '2.9', '3.0'),
            ...
            ]
        '''
        
        pygame.mixer.music.play()
        
        n=0
        tmpBool= True

        pos=  pygame.mixer.music.get_pos()
        while pos!=-1:

            pos=  pygame.mixer.music.get_pos() # in msec
            
            #print('pos= ',pos/L*sumT)

            # 重要音文同步計算公式
            iPos= int(pos/L*sumT) # 這就是我說的「正比關係」!!
            
            if n<len(Z):
                if iPos>=Z[n][2] and iPos<=Z[n][3] and tmpBool==True:

                    if n>=1:
                        tx.tag_remove('highlight',Z[n-1][4],Z[n-1][5])
                    tx.tag_add('highlight',Z[n][4],Z[n][5])
                    
                    tx.see(Z[n][5]) # 加這行,才能自動捲軸。
                    tx.update()     # 加這行,才能即時顯示效果。
                    
                    tmpBool= False
                    
                elif iPos >= Z[n][3]:
                    n+=1
                    tmpBool= True
  
    def ryQuit():
        pygame.mixer.music.stop()
        pygame.mixer.quit()

    def setButtons():
        
        bnShowText=  Button(text= 'ryShowText',  command= ryShowText)
        bnHighLight= Button(text= 'ryHighLight', command= ryHighLight)
        bnInit=      Button(text= 'ryInit',      command= ryInit)
        bnQuit=      Button(text= 'ryQuit',      command= ryQuit)
        bnPlay=      Button(text= 'ryPlay',      command= ryPlay)
        bnSync01=    Button(text= 'rySync01',    command= rySync01)
        bnSync02=    Button(text= 'rySync02',    command= rySync02)
        bnSync03=    Button(text= 'rySync03',    command= rySync03)


        bnShowText.pack( side='left')
        bnHighLight.pack(side='left')
        bnInit.pack(     side='left')
        bnQuit.pack(     side='left')
        bnPlay.pack(     side='left')
        bnSync01.pack(   side='left')
        bnSync02.pack(   side='left')
        bnSync03.pack(   side='left')


    #########################
    ryMain() # 真正執行在此。
Beispiel #38
0
def _color_delegator(parent):  # htest #
    from tkinter import Toplevel, Text
    from idlelib.Percolator import Percolator

    top = Toplevel(parent)
    top.title("Test ColorDelegator")
    top.geometry("200x100+%d+%d" %
                 (parent.winfo_rootx() + 200, parent.winfo_rooty() + 150))
    source = "if somename: x = 'abc' # comment\nprint\n"
    text = Text(top, background="white")
    text.pack(expand=1, fill="both")
    text.insert("insert", source)
    text.focus_set()

    p = Percolator(text)
    d = ColorDelegator()
    p.insertfilter(d)


if __name__ == "__main__":
    from tkinter import Tk, Text
    from idlelib.Percolator import Percolator
    root = Tk()
    text = Text(root)
    text.pack()
    d = ColorDelegator()
    p = Percolator(text)
    p.insertfilter(d)
    root.mainloop()
Beispiel #39
0
    def __init__(self, filename=None):
        self.root = root = turtle._root = Tk()
        root.title('Python turtle-graphics examples')
        root.wm_protocol("WM_DELETE_WINDOW", self._destroy)

        root.grid_rowconfigure(1, weight=1)
        root.grid_columnconfigure(0, weight=1)
        root.grid_columnconfigure(1, minsize=90, weight=1)
        root.grid_columnconfigure(2, minsize=90, weight=1)
        root.grid_columnconfigure(3, minsize=90, weight=1)

        self.mBar = Frame(root, relief=RAISED, borderwidth=2)
        self.ExamplesBtn = self.makeLoadDemoMenu()
        self.OptionsBtn = self.makeHelpMenu()
        self.mBar.grid(row=0, columnspan=4, sticky='news')

        pane = PanedWindow(orient=HORIZONTAL,
                           sashwidth=5,
                           sashrelief=SOLID,
                           bg='#ddd')
        pane.add(self.makeTextFrame(pane))
        pane.add(self.makeGraphFrame(pane))
        pane.grid(row=1, columnspan=4, sticky='news')

        self.output_lbl = Label(root,
                                height=1,
                                text=" --- ",
                                bg="#ddf",
                                font=("Arial", 16, 'normal'),
                                borderwidth=2,
                                relief=RIDGE)
        self.start_btn = Button(root,
                                text=" START ",
                                font=btnfont,
                                fg="white",
                                disabledforeground="#fed",
                                command=self.startDemo)
        self.stop_btn = Button(root,
                               text=" STOP ",
                               font=btnfont,
                               fg="white",
                               disabledforeground="#fed",
                               command=self.stopIt)
        self.clear_btn = Button(root,
                                text=" CLEAR ",
                                font=btnfont,
                                fg="white",
                                disabledforeground="#fed",
                                command=self.clearCanvas)
        self.output_lbl.grid(row=2, column=0, sticky='news', padx=(0, 5))
        self.start_btn.grid(row=2, column=1, sticky='ew')
        self.stop_btn.grid(row=2, column=2, sticky='ew')
        self.clear_btn.grid(row=2, column=3, sticky='ew')

        Percolator(self.text).insertfilter(ColorDelegator())
        self.dirty = False
        self.exitflag = False
        if filename:
            self.loadfile(filename)
        self.configGUI(NORMAL, DISABLED, DISABLED, DISABLED,
                       "Choose example from menu", "black")
        self.state = STARTUP
Beispiel #40
0
class ConsoleText(ScrolledText):
    class StreamObserver(object):
        def __init__(self, console_text):
            self.__console_text  = console_text
        def update(self, stream_type, content):
            self.__console_text.write(stream_type, content)
    
    def __init__(self, *args, **kwargs):
        super(ConsoleText, self).__init__(*args, **kwargs)
        # The shared queue of the PRODUCER-CONSUMER model.
        self.__queue    = Queue.Queue()
        self.text['wrap']   = 'word'
        self.text.tag_configure('STDOUT',   foreground='black')
        self.text.tag_configure('STDERR',   foreground='red')
        self.text.tag_configure('TIP', foreground='forestgreen')
        self.text.tag_configure('HISTORY',   foreground='purple')
        self.text.tag_configure('RETVAL',    foreground='orange')
        
        self.text.bind('<KeyPress>', self.on_key_press)

        
        # Experimenting with idlelib.AutoComplete
        #############################################################
        self.indent_width    = 4
        self.tab_width       = 4
        self.context_use_ps1    = '>>> '
        self.__auto_complete = AutoComplete(self)  
        #############################################################
                
        # Syntax highlight is implemented by idlelib
        #############################################################                
        self.percolator = Percolator(self.text)
        self.color_delegator = ColorDelegator()
        self.percolator.insertfilter(self.color_delegator)   
        #############################################################                        
        self.prompt_symbol = '>>> '    
        
        
    def update_content(self, tag, content):
        r, c    = self.get_cursor_pos(END)
        start   = 'end-5c'
        stop    = 'end-1c'
        if self.text.get(start, stop) == '>>> ' or self.text.get(start, stop) == '... ':
            self.text.delete(start, stop)

        # Record the position of the END before inserting anything.
        start    = self.text.index(END)

        self.text.insert(END, content, tag)

        # Remove unnecessary highlighting
        for tag in self.color_delegator.tagdefs:
            self.text.tag_remove(tag, start, "end")            
        self.text.insert(END, self.prompt_symbol)                
        # Remove unnecessary highlighting
        self.text.tag_remove("TODO", "1.0", END)
        self.text.tag_add("SYNC", "1.0", END)                                
        self.text.see(END)                        

    def on_key_press(self, evt, code_list=[]):     
        # Experimenting with idlelib's AutoComplete
        ##############################################################
        keysym = evt.keysym        
        if self.__auto_complete.autocompletewindow and \
                self.__auto_complete.autocompletewindow.is_active():
            if self.__auto_complete.autocompletewindow.keypress_event(evt) == 'break':
                return 'break'
            else:
                if keysym == 'Tab':
                    return 'break'
            
        if evt.keysym == 'Tab':
            return self.__auto_complete.autocomplete_event(evt)
        ##############################################################
        # if evt.keycode not in range(16, 19) and evt.keycode not in range(33, 41):
        if evt.keysym not in ('Alt_L', 'Alt_R', 'Control_L', 'Control_R', 'Shift_L', 'Shift_R',  'KP_Prior', 'KP_Next', 'KP_Home', 'KP_End', 'KP_Left', 'KP_Right', 'KP_Up', 'KP_Down', 'Left', 'Right', 'Up', 'Down', 'Home', 'End', 'Next', 'Prior'):
            r, c    = self.get_cursor_pos()
            prompt  = self.text.get(auto_subs('$r.0'), auto_subs('$r.4'))
            if prompt != '>>> ' and prompt != '... ':
                return 'break'
            if evt.keysym=='BackSpace' and c <= 4:
                return 'break'
            if c < 4:
                return 'break'
            rend, cend  = self.get_cursor_pos('end-1c')
            if r < rend:
                return 'break'                
            if evt.keysym == 'Return': # Return
                app = Application.instance
                code = self.text.get(auto_subs('$r.4'), auto_subs('$r.end'))
                try:
                    stripped_code     = code.strip()
                    if stripped_code and stripped_code[0] == '!':
                        # Execute a system command
                        app.execute(code)
                        self.prompt_symbol   = '>>> '
                        self.update_content(tag='', content='\n')
                        return 'break'
                    if stripped_code == '':
                        code = '\n'.join(code_list)
                        del code_list[:]
                    stripped_code = code.strip()
                    if stripped_code == '':
                        self.prompt_symbol   = '>>> '
                        self.update_content(tag='', content='\n') 
                    elif code_list or stripped_code[-1] in (':', '\\') or stripped_code[0] in ('@',): # Threre is a bug here for decorators! To do: Solve it.
                        code_list.append(code)
                        self.prompt_symbol   = '... '
                        self.update_content(tag='', content='\n')
                    else:
                        self.prompt_symbol   = '>>> '
                        self.update_content(tag='', content='\n')
                        try:
                            ret = app.execute(code)
                        except:
                            traceback.print_exc()
                        if ret is not None:
                            self.update_content(tag='RETVAL', content=repr(ret)+'\n')
    
                finally:
                    self.text.mark_set(INSERT, END)
                    self.text.see(END)
                    return 'break'            
                
    def get_cursor_pos(self, mark=INSERT): 
        return (int(i) for i in self.text.index(mark).split('.'))               
 def setUp(self):
     self.percolator = Percolator(self.text)
     self.filter_one = MyFilter()
     self.filter_two = MyFilter()
     self.percolator.insertfilter(self.filter_one)
     self.percolator.insertfilter(self.filter_two)