我正在使用 PyGI 编写一个小应用程序,它将在鼠标单击之间以交互方式在 Gtk.DrawingArea 上绘制一条线。但我不知道如何使用 cairo 上下文在鼠标单击事件返回的坐标处进行绘制。
应如何从“按钮按下事件”处理绘图以绘制类似于附加代码中的“绘制”回调产生的图案?
class MyApp(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Draw on button press")
self.set_size_request(800, 500)
self.connect('delete-event', Gtk.main_quit)
self.drawing_area = Gtk.DrawingArea()
self.drawing_area.add_events(Gdk.EventMask.BUTTON_PRESS_MASK)
self.drawing_area.connect('draw', self.on_drawing_area_draw)
self.drawing_area.connect('button-press-event', self.on_drawing_area_button_press)
self.drawing_area.show()
self.add(self.drawing_area)
self.show_all()
def on_drawing_area_button_press(self, widget, event):
print "Mouse clicked... at ", event.x, ", ", event.y
# How to draw a line starting at this point on the drawing area?
return True
def on_drawing_area_draw(self, drawing_area, cairo_context):
cairo_context.move_to(50, 50)
cairo_context.rel_line_to(0, 200)
cairo_context.rel_line_to(200, 0)
cairo_context.rel_line_to(0, -200)
cairo_context.set_source_rgb(0, 0, 0)
cairo_context.stroke()
return False
app = MyApp()
Gtk.main()
答案1
你应该做的是设置在绘制回调中绘制的变量。如果你想让它重新绘制自己,你可以使用它来强制它:
drawing_area.queue_draw()
编辑:以下是您可以使用的代码示例:
clicks = [];
def on_drawing_area_button_press(self, widget, event):
print "Mouse clicked... at ", event.x, ", ", event.y
clicks.append([event.x, event.y])
drawing_area.queue_draw()
return True
def on_drawing_area_draw(self, drawing_area, cairo_context):
cairo_context.move_to(50, 50)
for point in clicks
cairo_context.line_to(point[0], point[1])
cairo_context.stroke()
return False