3

gedit geany と rhythmbox が機能するのと同じように、python アプリケーション内に python インタープリターを埋め込む最善の方法についての提案を探しているので、その場でプログラムを変更できます。?

4

2 に答える 2

0

これは、将来の使用のために思いついたソリューションです:)

#!/usr/bin/env python
# [SNIPPET_NAME: gtk3 interactive textview]
# [SNIPPET_CATEGORIES: gtk]
# [SNIPPET_TAGS:interactive, gtk3]
# [SNIPPET_DESCRIPTION: using gtk3 textview run python code on running program]
# [SNIPPET_AUTHOR: Oliver Marks ]
# [SNIPPET_LICENSE: GPL]

from gi.repository import Gtk, Gdk
import code
import math


class interactiveGtk:
    def __init__(self):
        window = Gtk.Window()
        window.set_default_size(380, 300)
        window.connect("destroy", lambda w: Gtk.main_quit())

        box = Gtk.VBox()

        self.drawingarea = Gtk.DrawingArea()

        textarea = Gtk.TextView()
        textarea.connect('key-press-event', self.key_pressed)
        self.textbuffer = textarea.get_buffer()
        self.textbuffer.set_text('self.show_drawing(True)')

        self.drawingarea.connect("draw", self.area_expose_cb)

        box.add(self.drawingarea)
        box.add(textarea)

        window.add(box)
        window.show_all()

        self.drawarea = False

        """interactive mode interpreter, pass locals() so we can access our programs functions and variables"""
        self.interpreter = code.InteractiveInterpreter(locals())

    def show_drawing(self, state):
        """self.show_drawing(True) to enable showing the lines"""
        self.drawarea = state

    def test(self):
        """run self.test() when program is running to print this message"""
        print 'hello world'

    def area_expose_cb(self, widget, context):
        """expose event lets draw, lines will only display if we run self.show_lines first.
        demonstrating running state change of our program"""
        self.style = self.drawingarea.get_style()
        #self.gc = self.style.fg_gc[Gtk.STATE_NORMAL]
        if self.drawarea is True:
            self.drawing(context, 210, 10)

    def drawing(self, cr, x, y):
        """ draw a circle in the drawing area """
        cr.set_line_width(10)
        cr.set_source_rgb(0.5, 0.8, 0.0)

        cr.translate(20 / 2, 20 / 2)
        cr.arc(50, 50, 50, 0, 2 * math.pi)
        cr.stroke_preserve()

        cr.set_source_rgb(0.3, 0.4, 0.4)
        cr.fill()

    def key_pressed(self, widget, event):
        """keypresses only intrested in return, run code in textview on return"""
        if event.keyval == Gdk.keyval_from_name('Return'):
            start = self.textbuffer.get_iter_at_line(0)
            lineend = start.get_chars_in_line()
            end = self.textbuffer.get_end_iter()
            source = self.textbuffer.get_text(start, end, False)

            """run our code in the textview widget, put output in the terminal we may want to put this into the gui somewhere"""
            print self.interpreter.runsource(source, "<<console>>")


interactiveGtk()
Gtk.main()
于 2013-07-14T21:13:05.817 に答える