2
尋找關於在python應用程序中嵌入python解釋器的最佳方式的建議,與gedit geany和rhythmbox的工作方式相同,因此您可以即時修改程序。 ?用於gtk應用程序的交互式Python控制檯
尋找關於在python應用程序中嵌入python解釋器的最佳方式的建議,與gedit geany和rhythmbox的工作方式相同,因此您可以即時修改程序。 ?用於gtk應用程序的交互式Python控制檯
This recipe是我6年前寫的東西,從那以後還沒有更新(或使用過),所以我不能真正推薦它作爲「回答」你的問題,但它可能會提供一些線索,你可以解決這個問題。希望它有幫助,祝你好運!
這是我想出了爲將來使用:)
#!/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()
感謝我有一個工作示例程序,我將在下面發佈,使用GTK 3使用一個TextView測試示例中的解決方案:) – Oly