【发布时间】:2016-10-08 11:26:54
【问题描述】:
我有一个问题,可能与模块无关。
在下面的代码中,有一个函数更新,它将通过matplotlib创建一个画布,并将其分配给来自tkinter的相关框架。然后它创建一个事件处理程序 Cursor,它将鼠标的位置打印到控制台中。但事实并非如此。但是,如果您删除方法更新并在模块主体中使用用于创建图形、光标和连接的行,一切都会正常工作。
我错过了什么?我想这是Python的基本知识,可见性和传递正确的实例,我不知道。
import matplotlib.pyplot as plt
from tkinter import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class Cursor (object):
def __init__ (self, fig):
self.fig = fig
print ("initializing")
def mouse_move (self, event):
if not event.inaxes:
return
x, y = event.xdata, event.ydata
print (x, y)
def connect (self):
print ("Connecting")
self.conmove = self.fig.canvas.mpl_connect ('motion_notify_event', self.mouse_move)
def pyplot_f ():
fig = plt.figure(figsize=(6,4), dpi=100)
axes = fig.add_subplot (111)
axes.plot([1,2,3,4], [1,2,3,4])
Canvas = FigureCanvasTkAgg (fig, master=frame_output)
canvas = Canvas.get_tk_widget()
canvas.grid(row=0,column=0, padx=5, pady=5, sticky="nesw")
return fig
w_width = 1000
w_height = 600
root = Tk()
root.resizable(0,0)
frame_output = Frame (root, bg="", relief=SUNKEN, width=w_width*0.8, height=w_height*0.9)
frame_output.grid(row=0, column=0, padx=20, pady=20, sticky=W+N+E+S)
frame_input = Frame (root, bg="", relief=RAISED,width=w_width*0.2, height=w_height*0.9)
frame_input.grid(row=0, column=1, padx=20, pady=20, sticky=W+N+E+S)
def update ():
fig = pyplot_f()
cursor = Cursor(fig)
cursor.connect()
def on_closing():
print ("Exiting")
root.quit()
update()
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
【问题讨论】:
标签: python matplotlib tkinter