def __init__(self, canvas,root,parent): self.canvas = canvas self.root = root self.parent = parent NavigationToolbar2TkAgg.__init__(self, canvas,root) self.lasso_button = self._custom_button(text="lasso",command=lambda: self.lasso( lambda inds: self.parent.multi_select_callback(inds),"lasso"),**DEFAULT_STYLE_1) self.pick_button = self._custom_button(text="select",command=lambda: self.picker( lambda ind: self.parent.single_select_callback(ind),"select"),**DEFAULT_STYLE_1)
def __init__(self, canvas,root,parent): self.canvas = canvas self.root = root self.parent = parent font = tkFont.Font(weight="bold",underline=True) NavigationToolbar2TkAgg.__init__(self, canvas,root) style = {"bg":"darkblue","fg":"gray90"} self.lasso_button = self._custom_button(text="lasso",command=lambda: self.lasso( lambda inds: self.parent.multi_select_callback(inds),"lasso"),**style) self.pick_button = self._custom_button(text="select",command=lambda: self.picker( lambda ind: self.parent.single_select_callback(ind),"select"),**style )
def __init__(self,canvas_,parent_): self.toolitems = ( ('Home', 'home', 'home', 'home'), ('Back', 'back', 'back', 'back'), ('Forward', 'forward', 'forward', 'forward'), (None, None, None, None), ('Pan', 'pan', 'move', 'pan'), ('Zoom', 'zoom', 'zoom_to_rect', 'zoom'), (None, None, None, None), ('Save', 'save', 'filesave', 'save_figure'), ) NavigationToolbar2TkAgg.__init__(self,canvas_,parent_)
def __init__(self, canvas_, parent_): # TODO: make normal buttons later self.toolitems = ( ('Home', '', 'home', 'home'), # ('Back', '', 'back', 'back'), # ('Forward', '', 'forward', 'forward'), # (None, None, None, None), # ('Pan', '', 'move', 'pan'), # ('Zoom', '', 'zoom_to_rect', 'zoom'), # (None, None, None, None), # ('Subplots', '', 'subplots', 'configure_subplots'), ('Save', '', 'filesave', 'save_figure'), ) NavigationToolbar2TkAgg.__init__(self, canvas_, parent_)
class MainWindow: def __init__(self, master=None): self.frame = tkinter.Frame(master) self.frame.pack(padx=15,pady=15) self.fig = matplotlib.figure.Figure(figsize=(6, 4), dpi=100) self.ax = self.fig.add_subplot(111) self.ax.plot(np.linspace(0, 4), np.sin(np.linspace(0, 4))) self.canvas = FigureCanvas(self.fig, master=self.frame) self.canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1) self.mpl_toolbar = NavigationToolbar(self.canvas, master) self.mpl_toolbar.update() self.canvas._tkcanvas.pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
def init_graph_area(self, plt_props, toolbox_frame): """ take the tkinter Frame (self) and embed a pyplot figure into it :param plt_props: dictionary of properties of the pyplot :return: bind figure and axis to this instance """ self.graph_area.figure_bed = plt.figure(figsize=(7, 4)) self.graph_area.axis = plt.subplot(111) # self.graph_area.axis.set_autoscalex_on(True) # self.graph_area.axis.set_autoscaley_on(True) self.lines, = self.graph_area.axis.plot([], []) self.graph_area.axis.format_coord = lambda x, y: "" # remove the coordinates in the toolbox """ go through the plot properties and apply each one that is listed """ for key, value in plt_props.iteritems(): eval("plt." + key + "(" + value + ")") # """ get the limits of the x axis from the parameters if they are not in the properties """ # if "xlim" not in plt_props: # plt.xlim(self.params['low_cv_voltage'], self.params['high_cv_voltage']) # plt.ylim(0, 2) """ format the graph area, make the canvas and show it """ self.graph_area.figure_bed.set_facecolor('white') self.graph_area.canvas = FigureCanvasTkAgg(self.graph_area.figure_bed, master=self) self.graph_area.canvas._tkcanvas.config(highlightthickness=0) """ Make a binding for the user to change the data legend """ # uncomment below to start making a data legend editor # self.graph_area.canvas.mpl_connect('button_press_event', self.legend_handler) """ Make the toolbar and then unpack it. allow the user to display or remove it later """ self.toolbar = NavToolbar(self.graph_area.canvas, toolbox_frame) self.toolbar.pack_forget() self.graph_area.canvas.draw() self.graph_area.canvas.get_tk_widget().pack(side='top', fill=tk.BOTH, expand=1)
def __init__(self, canvas_, parent_): self.toolitems = ( ("New", "New File", "new_file", "new_file"), ("Save", "Save File", "save_file", "save_figure"), ("Print", "Print", "printer", "print_figure"), (None, None, None, None), ("Home", "Home", "home", "home"), ("Refresh", "Refresh", "refresh", "refresh"), ("Backward", "Backward", "back3", "back"), ("Play", "Play", "play4", "play"), ("Forward", "Forward", "forward2", "forward"), ("Plot", "Plot", "plot", "plot"), (None, None, None, None), ("Move", "Move", "move", "pan"), ("Rotate", "Rotate", "rotate", "rotate"), ("Zoom in", "Zoom in", "zoom_in", "zoom_in"), ("Zoom out", "Zoom out", "zoom_out", "zoom_out"), (None, None, None, None), ("Subplots", "Subplots", "subplots2", "configure_subplots"), ) NavigationToolbar2TkAgg.__init__(self, canvas_, parent_)
def __init__(self, master=None, title=None, ): super(NetworkPlotTk, self).__init__( matplotlib_figure=matplotlib.figure.Figure(), ) if master is None: master = tk.Tk() master.withdraw() self.master = master #self.master.protocol("WM_DELETE_WINDOW", self.on_closing) # Create a Toplevel widget, which is a child of GUILoom # and contains plots, self.toplevel = tk.Toplevel(master) self.toplevel.wm_title(title) self.toplevel.protocol("WM_DELETE_WINDOW", self.on_closing) self.plot_idx_scale = None self.plot_idx_entry = None self.plot_idx_entry_var = tk.StringVar() self.plot_idx_entry_var.trace('w', self.plot_idx_entry_change) self.canvas = FigureCanvas( self.figure, master=self.toplevel, resize_callback=self.canvas_resize_callback ) self.canvas.show() self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) toolbar = NavigationToolbar(self.canvas, self.toplevel) toolbar.update() self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
def cine_disp(self): os.chdir(self.script_dir) img = self.cine_images[:, :, 0, 0] #print(img.shape) #print("image min = %f" % img.min()) #print("image max = %f" % img.max()) fig = Figure(figsize=(5,5)) ax0 = fig.add_subplot(111) ax0.imshow(img, cmap=plt.cm.gray) self.canvas_cine = FigureCanvasTkAgg(fig, self.disp_cine_img) self.canvas_cine.show() self.canvas_cine.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) self.toolbar_cine = NavigationToolbar2TkAgg(self.canvas_cine, self.disp_cine_img) self.toolbar_cine.update() self.canvas_cine._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True) self.cine_ax0 = ax0
def __init__(self, master, data): tk.Frame.__init__(self, master=master) self.index = 1 self.lines = [] self.labels = [] self.colors = [] self.vert_line = None self.data = data self.cursor_connect = None self.graph_area = tk.Frame(self) self.figure_bed = plt.figure(figsize=(6, 4)) self.axis = self.figure_bed.add_subplot(111) self.canvas = FigureCanvasTkAgg(self.figure_bed, master=self) self.canvas._tkcanvas.config(highlightthickness=0) self.toolbar = NavToolbar(self.canvas, self) # TODO: check this # self.toolbar.pack_forget() self.toolbar.pack() self.canvas.draw() self.canvas.get_tk_widget().pack(side='left', fill=tk.BOTH, expand=1)
def ext_entry(): num_init = [1, 2, 3, 4, 5] args = (0.1, 0.2, 0.3, 0.4, 0.5) t = np.linspace(0, 50, 5000) X = integrate.odeint(ext_solvr, num_init, t, args) fig = Figure() a = fig.add_subplot(111) ax = a.plot(t, X) a.set_xlabel('time') a.set_ylabel('population') a.legend(ax, ['A', 'B', 'C', 'D', 'E'], loc=0) root = Tk() canvas = FigureCanvasTkAgg(fig, master=root) canvas.show() canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) toolbar = NavigationToolbar2TkAgg(canvas, root) toolbar.update() canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)
def __init__(self, parent, controller): tk.Frame.__init__(self,parent) canvas = FigureCanvasTkAgg(f, self) canvas.show() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) toolbar = NavigationToolbar2TkAgg(canvas, self) toolbar.update() canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True) video_on_button = tk.Button(self, text="Start video processing", command=lambda: main.img_proccessor(True)) video_on_button.pack() video_off_button = tk.Button(self, text="Stop video processing", command=lambda: main.img_proccessor(False)) video_off_button.pack() exit_button = tk.Button(self, text="Exit", command=self.client_exit) exit_button.pack()
def HideAtom(): Store_all = [] with open(execution_path('1rgs.cif')) as protein: for lines in protein: if "ATOM " in lines: lines = lines.split() Store_all.append(map(float, lines[10:13])) x, y, z = zip(*Store_all) fig = Figure(figsize=(10, 6), dpi=100, facecolor='black') canvas = FigureCanvasTkAgg(fig, self) canvas.draw() plt = fig.add_subplot(111, projection="3d") plt.set_axis_bgcolor("black") plt.plot(x, y, z) #plt.show() plt.axis("off") toolbarFrame = Frame(self) toolbarFrame.grid(row=6, column=7) toolbar = NavigationToolbar2TkAgg(canvas, toolbarFrame) canvas.get_tk_widget().grid(row=4, column=7)
def calibration_volatility_logreturn_show(self): if self.entry_type.get() == 'call': picture1, picture2 = Heston_variance_plot(self.kappa, self.theta, self.sigma, self.rho, self.v0) kappa = self.kappa theta = self.theta sigma = self.sigma rho = self.rho v0 = self.v0 if self.entry_type.get() == 'put': picture1, picture2 = Heston_variance_plot(self.kappa2, self.theta2, self.sigma2, self.rho2, self.v02) kappa = self.kappa2 theta = self.theta2 sigma = self.sigma2 rho = self.rho2 v0 = self.v02 tk = Toplevel() tk.geometry('800x800') canvas = FigureCanvasTkAgg(picture1, master=tk) canvas.show() canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) canvas = FigureCanvasTkAgg(picture2, master=tk) canvas.show() canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) Label(tk, text="Kappa:%.4f Theta:%.4f Sigma:%.4f rho:%.4f v0:%.4f" % (kappa, theta, sigma, rho, v0)).pack(side=TOP, fill=BOTH, expand=1) toolbar = NavigationToolbar2TkAgg(canvas, tk) toolbar.update() canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)
def createWidgets(self): # a tk.DrawingArea canvas = FigureCanvasTkAgg(f, master=root) canvas.show() canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) toolbar = NavigationToolbar2TkAgg(canvas, root) toolbar.update() canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.QUIT = Tk.Button(self) self.QUIT["text"] = "QUIT" self.QUIT["fg"] = "red" self.QUIT["command"] = self.quit self.QUIT.pack({"side": "left"}) self.hi_there = Tk.Button(self) self.hi_there["text"] = "Hello", self.hi_there["command"] = self.say_hi self.hi_there.pack({"side": "left"})
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.pack_propagate(0) global pontos_newton label = tk.Label(self, text="Graph Page!", font=LARGE_FONT) label.pack(pady=10, padx=10) button1 = ttk.Button(self, text="Back to Home", command=lambda: controller.show_frame(StartPage)) button1.pack() f = Figure(figsize=(5, 5), dpi=100) a = f.add_subplot(111) a.plot([1, 2, 3, 4, 5, 6, 7, 8], [5, 6, 1, 3, 8, 9, 3, 5]) canvas = FigureCanvasTkAgg(f, self) canvas.show() canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) toolbar = NavigationToolbar2TkAgg(canvas, self) toolbar.update() canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
def setupWindow(self): self.f_inp = Frame(self.mwin) self.f_inp.pack(side='left') self.f_plot = Frame(self.mwin) self.f_plot.pack(side='right') self.c = FigureCanvasTkAgg(self.fig, master=self.f_plot) self.c.show() self.c.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) # setup the input area self.f_actn = LabelFrame(self.f_inp, text='action') self.f_actn.grid(row=0, column=0) self.f_gg = Frame(self.f_actn) self.f_gg.pack() l_gg = Label(self.f_gg, text='generations') l_gg.pack() self.e_gg = Entry(self.f_gg) self.e_gg.pack() self.e_gg.insert(0, '40') # number of generations self.b_rini = Button(self.f_actn, text='randini', command=self.randini) self.b_rini.pack() self.b_run1 = Button(self.f_actn, text='update & run', command=self.run_with_readout) self.b_run1.pack() self.b_run2 = Button(self.f_actn, text='run (continue)', command=self.run_no_readout) self.b_run2.pack() if len(self.vl): self.add_entries(self.vl) # draw initial plot self.draw_ini_solu( ) # sort of setting up instructive initial geometry plot of non-optimised geometry self.acp_ini() self.f_tb = Frame(self.f_plot) self.f_tb.pack() self.tb = NavigationToolbar2TkAgg(self.c, self.f_tb) self.c2 = Canvas(self.f_inp, width=80, height=140) self.c2.grid(row=4, column=0) self.ini_mstep_bar()
def __init__(self, master, name, data): tk.Toplevel.__init__(self, master) self.wm_title("CDF: {}".format(name)) self.fig = Figure(figsize=(4, 3), dpi=100) canvas = FigureCanvasTkAgg(self.fig, self) canvas.get_tk_widget().pack(fill=tk.BOTH, expand=1) toolbar = NavigationToolbar2TkAgg(canvas, self) menubar = tk.Menu(self) menubar.add_command(label="Save Data", command=self.save) self.config(menu=menubar) ax = self.fig.gca() ax.set_title(name) self.x, self.y = ae.cdf(data) ax.plot(self.x, self.y, "o") ax.loglog() ax.grid(True) self.update()
def __init__(self, parent, figsize=(5, 4), dpi=100, bind_keys=False, show_toolbar=False): # Cal the init function of tkinter's Frame Tk.Frame.__init__(self, parent) # Create a matplotlib Figure self.fig = Figure(figsize=figsize, dpi=dpi) # Create a matplotlib subplot self.subplot = self.fig.add_subplot(111) # Create and draw a canvas self.canvas = FigureCanvasTkAgg(self.fig, master=self) self.canvas.draw() # Add a toolbar if needed if show_toolbar: toolbar = NavigationToolbar2TkAgg(self.canvas, self) toolbar.update() # Pack the canvas in the Frame self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) self.canvas._tkcanvas.pack(side=Tk.BOTTOM, fill=Tk.BOTH, expand=1) # Bind keyboard shortcuts if bind_keys: def on_key_press(event): key_press_handler(event, self.canvas, toolbar) self.canvas.mpl_connect("key_press_event", on_key_press)
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Graph Page", font=titleFont) label.pack(pady=10, padx=10) self.f = Figure(figsize=(5, 5), dpi=100) self.plt = self.f.add_subplot(111) # self.plt.plot([1, 2, 3, 4, 5, 6, 7, 8], [5, 6, 1, 3, 8, 9, 3, 5]) canvas = FigureCanvasTkAgg(self.f, self) canvas.show() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) button1 = ttk.Button(self, text="Back to Home", command=lambda: controller.show_frame(MainMenu)) button1.pack(side=tk.BOTTOM, expand=True) toolbar = NavigationToolbar2TkAgg(canvas, self) toolbar.update() canvas._tkcanvas.pack(fill=tk.BOTH, expand=True)
def __init__(self, root, controller): f = Figure() ax = f.add_subplot(111) ax.set_xticks([]) ax.set_yticks([]) ax.set_xlim((x_min, x_max)) ax.set_ylim((y_min, y_max)) canvas = FigureCanvasTkAgg(f, master=root) canvas.show() canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) canvas.mpl_connect('button_press_event', self.onclick) toolbar = NavigationToolbar2TkAgg(canvas, root) toolbar.update() self.controllbar = ControllBar(root, controller) self.f = f self.ax = ax self.canvas = canvas self.controller = controller self.contours = [] self.c_labels = None self.plot_kernels()
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) tk.Label(self, text="RMS parameter histogram", font=LARGE_FONT).pack(pady=10, padx=10) ttk.Button(self, text="Back", command=lambda: controller.show_frame(StartPage)).pack() f = Figure(figsize=(5, 5), dpi=100) a = f.add_subplot(111) from_sensors = np.loadtxt(sensor_data_path, delimiter=",") rms_list = [i[1] for i in from_sensors] a.hist(rms_list, bins=40) canvas = FigureCanvasTkAgg(f, self) canvas.show() canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) toolbar = NavigationToolbar2TkAgg(canvas, self) toolbar.update() canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
def open_rectification_Slave(): fileName = tkFileDialog.askopenfilename( title='select slave image to be rectified') global fx global ax fx = Figure(figsize=(5, 4), dpi=100) ax = fx.add_subplot(111) img = mpimg.imread(fileName) ax.imshow(img) # a tk.DrawingArea global canvasx canvasx = FigureCanvasTkAgg(fx, master=Root1) canvasx.show() canvasx.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) toolbar = NavigationToolbar2TkAgg(canvasx, Root1) toolbar.update() canvasx._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) def on_key_event(event): print('you pressed %s' % event.key) key_press_handler(event, canvasx, toolbar) fx.canvas.mpl_connect('button_press_event', mouse_input_eventx) fx.canvas.mpl_connect('key_press_event', on_key_event) def _quitx(): Root1.quit() # stops mainloop Root1.destroy() # this is necessary on Windows to pprevent # Fatal Python Error: PyEval_RestoreThread: NULL tstate button1 = tk.Button(master=Root1, text='Quit', command=_quitx) button1.pack(side=tk.BOTTOM) button = tk.Button(master=Root1, text='select', command=clickx) button.pack(side=tk.BOTTOM)
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label( self, text="Welcome to the best morse decoder in the entire world!", fg="blue", font=LARGE_FONT) label.pack(pady=20, padx=10) button_load = Button(self, text="Load audio", command=plot_audio, height=1, width=13) button_load.pack() button_graph = Button( self, text="Show more graphs", command=lambda: controller.show_frame(graphs_page), height=1, width=13) button_graph.pack(padx=4, pady=10) button_graph2 = Button( self, text="Show sound graph", command=lambda: controller.show_frame(graphs_page2), height=1, width=13) button_graph2.pack() canvas = FigureCanvasTkAgg(forma2, self) canvas.show() canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) #barra de navegación matplotlib toolbar = NavigationToolbar2TkAgg(canvas, self) toolbar.update() canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
def plot_data(self,dollars): """ This function takes in a list for dollars calculates the years and converts the lists into numpy arrays and plots them onto a matplotlib figure embedded into tkinter. """ #create a figure object to hold the matplotlib plots self.figure = Figure(figsize=(5,4), dpi = 100) #create a subplot first row first column self.a = self.figure.add_subplot(111) #update the list of dollars for the plot self.dollars = np.array(dollars) self.years = np.arange(0,len(dollars),1) #plots the numpy arrays into a matplotlib figure 'pyplot' self.a.plot(self.years,self.dollars,linestyle='none',marker='o') #holds matplotlib figure in a container to be displayed in tkinter window 'window' self.canvas = FigureCanvasTkAgg(self.figure,master=self) #show matplotlib figure on tkinter window self.canvas.show() #displays the matplotlib figure on the grid self.canvas.get_tk_widget().grid(row=10,column=1,columnspan=3,rowspan=20) #create the toolbar synced with canvas self.toolbarFrame = tk.Frame(self) self.toolbarFrame.grid(row=31,column=1) #creates a navigation toolbar linked to the matplotlib figure with #the master being the toolbar tk.Frame self.toolbar = NavigationToolbar2TkAgg(self.canvas,self.toolbarFrame) #update the plot self.toolbar.update()
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) # add text to window label = tk.Label(self, text="Graph Page", font=LARGE_FONT) label.pack(pady=10, padx=10) # adding paddings around to look neat button1 = ttk.Button(self, text="Back to Home", command=lambda: controller.show_frame(StartPage)) button1.pack() # plot data in background #f = Figure(figsize=(5,5), dpi=100) #a = f.add_subplot(111) #a.plot([1,2,3,4,5,6,7,8],[5,6,1,3,8,9,3,5]) #make plt.show() show up on canvas canvas = FigureCanvasTkAgg(f, self) canvas.show() canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True) toolbar = NavigationToolbar2TkAgg(canvas, self) toolbar.update() canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
def __init__(self, root, listener=None): self.root = root fig, ax = plt.subplots(figsize=(6, 6)) self.ax = ax self.ax.set_xlim([0, 255]) self.ax.set_ylim([0, 255]) browser = ToneCurve(fig, self.ax, listener) plot_frame = Frame(self.root) self.root.add(plot_frame) canvas = FigureCanvasTkAgg(fig, master=plot_frame) canvas.mpl_connect('pick_event', browser.onpick) canvas.mpl_connect('motion_notify_event', browser.on_motion) #both bind is very important for release event but I do not know why canvas._tkcanvas.bind('button_release_event', browser.on_release) canvas.mpl_connect('button_release_event', browser.on_release) toolbar = NavigationToolbar2TkAgg(canvas, plot_frame) toolbar.update() self.canvas = canvas self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Results", font=LARGE_FONT) label.pack(pady=10, padx=10) button1 = ttk.Button(self, text="Back", command=lambda: controller.show_frame(StartPage)) button1.pack() button4 = ttk.Button(self, text="Analyze", command=self.parseData) button4.pack() self.canvas = FigureCanvasTkAgg(f, self) self.canvas.show() self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) toolbar = NavigationToolbar2TkAgg(self.canvas, self) toolbar.update() self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
def widgetwindow(ctr): Leftframe = tk.Frame(root) Leftframe.pack() Rightframe = tk.Frame(root) Rightframe.pack(side=tk.RIGHT) w1 = tk.Scale(Leftframe, from_=0.0, to=1.0, resolution=0.1, orient=tk.HORIZONTAL, length=200) w1.grid(row=0) w2 = tk.Scale(Leftframe, from_=3.0, to=8.0, resolution=0.1, orient=tk.HORIZONTAL, length=200) w2.grid(row=2, column=0) MinValue = ttk.Button(Leftframe, text="Set Min Value", command=lambda: printsilder(w1)) MinValue.grid(row=1, column=0) MaxValue = ttk.Button(Leftframe, text="Set Max Value", command=lambda: printsilder(w2)) MaxValue.grid(row=3, column=0) canvas = FigureCanvasTkAgg(f, Rightframe) canvas.show() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) toolbar = NavigationToolbar2TkAgg(canvas, Rightframe) toolbar.update() canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
def new_window(): id = "Graph" window = Toplevel(master) label = ttk.Label(window, text=id) label.pack(side="top", fill="both", padx=10, pady=10) f = Figure(figsize=(5, 5), dpi=100) a = f.add_subplot(111) # t = arange(0.0,3.0,0.01) # s = sin(2*pi*t) # a.plot(t,s) a.plot([1, 2, 3, 4, 5], [evalue[0], evalue[1], evalue[2], evalue[3], evalue[4]]) a.set_title('Emotion Scores') a.set_xlabel('1 - > Happiness , 2 - > Anger , 3 - > Sadness , 4 - > Fear , 5 - > Disgust ') a.set_ylabel('Score') # a tk.DrawingArea canvas = FigureCanvasTkAgg(f, master=window) canvas.show() canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) toolbar = NavigationToolbar2TkAgg(canvas, window) toolbar.update() canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1) def on_key_event(event): print('you pressed %s' % event.key) key_press_handler(event, canvas, toolbar) canvas.mpl_connect('key_press_event', on_key_event) def _quit(): window.quit() # stops mainloop window.destroy() # this is necessary on Windows to prevent # Fatal Python Error: PyEval_RestoreThread: NULL tstate button = ttk.Button(master=window, text='Quit', command=_quit) button.pack(side=BOTTOM)
def __init__(self, parent, controller, figure=settings.fig): tk.Frame.__init__(self, parent) defaultbg = self.cget('bg') # self -> from AcousticStand class figure.set_facecolor(defaultbg) # highlightborder doesn't work because of bugs/incopletions in ttk. # there are wrappers for this (from tk) but... bez przesady ttk_style = ttk.Style() ttk_style.configure('Mine.TButton', highlightthickness=1, # doesn't work ) ttk_style.map('Mine.TButton', relief=[('pressed', 'sunken'), ('!pressed', 'raised')], background=[('pressed', '#ffebcd')], foreground=[('active', 'green'), # by mouse ('focus','green')], # by keyboard ) canvas = FigureCanvasTkAgg(figure, self) canvas.show() canvas.get_tk_widget().pack(side="bottom") button_home = ttk.Button( self, text="About the project", width=14, takefocus=1, style='Mine.TButton', command=lambda: controller.show_frame(InfoPage)) button_home.pack(side="left") self.button_record = ttk.Button(self, width=14, text='Record data', style='Mine.TButton', command=lambda: self.call_record()) self.button_record.pack(side="left") toolbar = NavigationToolbar2TkAgg(canvas, self) toolbar.update() canvas._tkcanvas.pack(side="bottom", fill="both", expand=True)
def create_plot_area(self, frame): """ Creates the plotting area and the ploting variables. """ xlabel = 'Time' ylabel = 'Temperature (K)' self.time_array = [datetime.datetime.now()] self.temperature_array = [0] self.setpoint_array = [0] f = plt.figure(figsize=(9, 8), dpi=72) self.T_plot = plt.subplot(111, ylabel=ylabel, xlabel=xlabel) self.T_plot.grid( True, color='gray' ) # This is the grid of the plot, not the placing comand self.T_plot.plot(self.time_array, self.setpoint_array, label='Set Point') self.T_plot.plot(self.time_array, self.temperature_array, 'o', label='Temperature') f.autofmt_xdate() myFmt = mdates.DateFormatter('%H:%M:%S') self.T_plot.xaxis.set_major_formatter(myFmt) self.T_plot.legend(loc='lower left') f.tight_layout() self.canvas = FigureCanvasTkAgg(f, frame) self.canvas.get_tk_widget().pack() self.canvas.show() toolbar = NavigationToolbar2TkAgg(self.canvas, frame) toolbar.update() self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
def drawPic(self): '''根据恒生指数成分股数据画出条形图,属于动态图''' self.fig = Figure(figsize=(16, 8), dpi=100) self.ax = self.fig.add_subplot(111) self.canvas = FigureCanvasTkAgg(self.fig, master=self) self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1) toolbar = NavigationToolbar2TkAgg(self.canvas, self) toolbar.update() footframe = tk.Frame(master=self).pack(side=tk.BOTTOM) self.footframe = footframe tk.Button(master=footframe, text='3D', command=self.bar_3d, bg='green').pack(side=tk.RIGHT, expand=1, pady=2) #side=tk.BOTTOM) tk.Button(master=footframe, text='退出', command=self._quit, bg='red').pack(side=tk.RIGHT, expand=1, pady=2) #side=tk.BOTTOM) tk.Button(master=footframe, text='排序', command=self.plot_show, bg='green').pack(side=tk.RIGHT, expand=1, pady=2) #side=tk.BOTTOM) tk.Button(master=footframe, text='折线图', command=self.zhexian, bg='green').pack(side=tk.RIGHT, expand=1, pady=2) tk.Button(master=footframe, text='刷新', command=self.update_sleep, bg='green').pack(side=tk.RIGHT, expand=1, pady=1) mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体 mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 self.tk_show_thread() # 绘图
def plotAsteroids(x, y): root = Tk.Tk() root.wm_title("Asteroids") #f = Figure(figsize=(5, 4), dpi=100) fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection='scatter_density') #a.plot(x,y,"o") #ax.plot(input) ax.scatter_density(x, y) ax.set_xlim(-5, 10) ax.set_ylim(-5, 10) # a tk.DrawingArea canvas = FigureCanvasTkAgg(fig, master=root) canvas.show() canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) toolbar = NavigationToolbar2TkAgg(canvas, root) toolbar.update() canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) def on_key_event(event): print('you pressed %s' % event.key) key_press_handler(event, canvas, toolbar) canvas.mpl_connect('key_press_event', on_key_event) def _quit(): root.quit() # stops mainloop root.destroy() # this is necessary on Windows to prevent # Fatal Python Error: PyEval_RestoreThread: NULL tstate button = Tk.Button(master=root, text='Quit', command=_quit) button.pack(side=Tk.BOTTOM) Tk.mainloop()
def __init__(self, root, g, title): self.popup = Toplevel(root) self.popup.focus_set() self.popup.title(title) self.title = title # do this better self.popup.resizable(False,False) self.frame1 = Frame(self.popup) self.frame1.pack() canvas = FigureCanvasTkAgg(g.figure, master=self.frame1) canvas.show() canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) toolbar = NavigationToolbar2TkAgg( canvas, self.frame1 ) toolbar.update() canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1) frame2 = Frame(self.frame1) frame2.pack(side=TOP) def on_key_event(event): key_press_handler(event, canvas, toolbar) def close(event=None): self.popup.destroy() Button(frame2, text="Close", underline=0, command=close).pack(side=LEFT) canvas.mpl_connect('key_press_event', on_key_event) self.popup.bind("<Return>",close) self.popup.bind("<Escape>",close) self.popup.bind("<Alt-c>",close) self.popup.protocol("WM_DELETE_WINDOW", close)
def CGWgen(self): if self.sXA.get() != '' and self.sYA.get() != '': self.CGWg = Tk.Toplevel(self) y_data_set = self.pdchoice[str( self.sYA.get())].loc[:, str(self.sYC.get())] if self.sXA.get() != 'Index': x_data_set = self.pdchoice[str( self.sXA.get())].loc[:, str(self.sXC.get())] graph = Figure(figsize=(5, 5)) sub_graph = graph.add_subplot(111) if self.sGT.get() == 'Scatter': sub_graph.plot(x_data_set, y_data_set, 'o') elif self.sGT.get() == 'Histogram': sub_graph.hist(y_data_set, bins=int(self.sHB.get())) else: x_data_set = 'Index' graph = Figure(figsize=(5, 5)) sub_graph = graph.add_subplot(111) if self.sGT.get() == 'Scatter': sub_graph.plot(y_data_set, 'o') elif self.sGT.get() == 'Histogram': sub_graph.hist(y_data_set, bins=int(self.sHB.get())) canvas = FigureCanvasTkAgg(graph, self.CGWg) canvas.show() canvas.get_tk_widget().pack(expand=True) toolbar = NavigationToolbar2TkAgg(canvas, self.CGWg) toolbar.update() canvas._tkcanvas.pack(expand=True) CGW_OK = Tk.Button(self.CGWg, text='Close', command=lambda: self.CloseCGW()) CGW_OK.pack() self.CGWg.protocol("WM_DELETE_WINDOW", lambda: self.CloseCGW())
def __init__(self, master=None): self.master = master tk.Frame.__init__(self, self.master) self.fig = Figure(figsize=(5, 4), dpi=100) # RETINA BRO? self.canvas = FigureCanvasTkAgg(self.fig, self) self.canvas.show() self.canvas.get_tk_widget().grid(row=0, column=1) self.toolbar = NavigationToolbar2TkAgg(self.canvas, self) self.toolbar.update() self.toolbar.grid(row=7, column=1) self.plotLock = threading.Lock() self.ax = mplot3d.Axes3D(self.fig) self.ax.set_title( "Path of charged particle under influence of electric and magnetic fields" ) self.ax.set_xlabel('X') self.ax.set_ylabel('Y') self.ax.set_zlabel('Z')
def _construct_plot(self): # plot panel self.plotframe = ttk.Frame(self.main) self.plotframe.grid(column=1, row=0, sticky=(N, W, E, S)) self.figure = Figure(figsize=(10, 5), dpi=72) self.ax = self.figure.add_subplot(1, 1, 1) self.ax.set_aspect('equal') self.figure.subplots_adjust(left=0.09, right=0.96) self._canvas = FigureCanvasTkAgg(self.figure, master=self.plotframe) self._canvas.show() self._canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) self._toolbar = NavigationToolbar2TkAgg(self._canvas, self.plotframe) self._toolbar.update() self._canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1) def on_key_event(event): # print('you pressed %s' % event.key) key_press_handler(event, self._canvas, self._toolbar) self._canvas.mpl_connect('key_press_event', on_key_event)
def __init__(self,c,w,l,call): self.dispOpt=l self.myCallback=call NavigationToolbar2TkAgg.__init__(self,c,w)
def zoom(self): NavigationToolbar2TkAgg.zoom(self) self.mode = "" self.set_message(self.mode)
def pan(self): NavigationToolbar2TkAgg.pan(self) self.mode = "" self.set_message(self.mode)
class PyplotEmbed(tk.Frame): """ Class that will make a tkinter frame with a matplotlib plot area embedded in the frame """ def __init__(self, root, toolbox_frame, plt_props, _master_frame): """ Initialize the class with a parent of tkinter Frame and embed a pyplot graph in it The class also will have a list to hold the data series that is displayed :param toolbox_frame: tkinter frame that the toolbox can be shown in :param plt_props: properties of the pyplot :param _master_frame: the frame that is the master to this frame :return: """ self.displayed = False tk.Frame.__init__(self, master=_master_frame) # initialize with the parent class self.master = _master_frame self.label_instance = "" """ Make an area to graph the data """ self.graph_area = tk.Frame(self) """ initiate the pyplot area """ self.init_graph_area(plt_props, toolbox_frame) self.toolbar_status = False def init_graph_area(self, plt_props, toolbox_frame): """ take the tkinter Frame (self) and embed a pyplot figure into it :param plt_props: dictionary of properties of the pyplot :return: bind figure and axis to this instance """ self.graph_area.figure_bed = plt.figure(figsize=(7, 4)) self.graph_area.axis = plt.subplot(111) # self.graph_area.axis.set_autoscalex_on(True) # self.graph_area.axis.set_autoscaley_on(True) self.lines, = self.graph_area.axis.plot([], []) self.graph_area.axis.format_coord = lambda x, y: "" # remove the coordinates in the toolbox """ go through the plot properties and apply each one that is listed """ for key, value in plt_props.iteritems(): eval("plt." + key + "(" + value + ")") # """ get the limits of the x axis from the parameters if they are not in the properties """ # if "xlim" not in plt_props: # plt.xlim(self.params['low_cv_voltage'], self.params['high_cv_voltage']) # plt.ylim(0, 2) """ format the graph area, make the canvas and show it """ self.graph_area.figure_bed.set_facecolor('white') self.graph_area.canvas = FigureCanvasTkAgg(self.graph_area.figure_bed, master=self) self.graph_area.canvas._tkcanvas.config(highlightthickness=0) """ Make a binding for the user to change the data legend """ # uncomment below to start making a data legend editor # self.graph_area.canvas.mpl_connect('button_press_event', self.legend_handler) """ Make the toolbar and then unpack it. allow the user to display or remove it later """ self.toolbar = NavToolbar(self.graph_area.canvas, toolbox_frame) self.toolbar.pack_forget() self.graph_area.canvas.draw() self.graph_area.canvas.get_tk_widget().pack(side='top', fill=tk.BOTH, expand=1) def update_graph(self, x, y): _x = x[:len(y)] self.lines.set_xdata(_x[-10000:]) self.lines.set_ydata(y[-10000:]) self.graph_area.axis.relim() self.graph_area.axis.autoscale_view() self.graph_area.canvas.draw() # update the canvas where the data is being shown
def __init__(self, canvas, window): self.toolitems = [tool for tool in NavigationToolbar2TkAgg.toolitems if tool[0] in ('Pan', 'Save')] self.toolitems.reverse() NavigationToolbar2TkAgg.__init__(self, canvas, window)
def __init__(self, parent, canvas): self.parent = parent NavigationToolbar2TkAgg.__init__(self, canvas, window=parent)
class PyplotEmbed(tk.Frame): """ Class that will make a tkinter frame with a matplotlib plot area embedded in the frame """ def __init__(self, root, toolbox_frame, plt_props, _master_frame, _params): """ Initialize the class with a parent of tkinter Frame and embed a pyplot graph in it The class also will have a list to hold the data series that is displayed :param toolbox_frame: tkinter frame that the toolbox can be shown in :param plt_props: properties of the pyplot :param _master: the frame that is the master to this frame :param _params: parameters needed for setting up the class :return: """ tk.Frame.__init__(self, master=_master_frame) # initialize with the parent class self.master = _master_frame self.label_instance = "" """ Make an area to graph the data """ self.graph_area = tk.Frame(self) self.params = root.operation_params self.plotted_lines = [] # make a list to hold the Line2D to display in the graph self.data = root.data # alias the data for this class to the main data """ Create a list to hold the matplotlib lines """ # self.plotted_lines = [] # root.plotted_lines = self.plotted_lines self.params = _params self.legend_displayed = False """ initiate the pyplot area """ self.init_graph_area(plt_props, toolbox_frame) self.toolbar_status = False def init_graph_area(self, plt_props, toolbox_frame): """ take the tkinter Frame (self) and embed a pyplot figure into it :param plt_props: dictionary of properties of the pyplot :return: bind figure and axis to this instance """ self.graph_area.figure_bed = plt.figure(figsize=(5, 4)) self.graph_area.axis = plt.subplot(111) self.graph_area.axis.format_coord = lambda x, y: "" # remove the coordinates in the toolbox """ go through the plot properties and apply each one that is listed """ for key, value in plt_props.iteritems(): eval("plt." + key + "(" + value + ")") """ get the limits of the x axis from the parameters if they are not in the properties """ if "xlim" not in plt_props: plt.xlim(self.params['low_cv_voltage'], self.params['high_cv_voltage']) """ calculate the current limit that can be reached, which depends on the resistor value of the TIA assume the adc can read +- 1V (1000 mV)""" current_limit = 1000 / self.params['TIA_resistor'] # units: (mV/kohms) micro amperes plt.ylim(-current_limit, current_limit) """ format the graph area, make the canvas and show it """ self.graph_area.figure_bed.set_facecolor('white') self.graph_area.canvas = FigureCanvasTkAgg(self.graph_area.figure_bed, master=self) self.graph_area.canvas._tkcanvas.config(highlightthickness=0) """ Make a binding for the user to change the data legend """ # uncomment below to start making a data legend editor # self.graph_area.canvas.mpl_connect('button_press_event', self.legend_handler) """ Make the toolbar and then unpack it. allow the user to display or remove it later """ self.toolbar = NavToolbar(self.graph_area.canvas, toolbox_frame) self.toolbar.pack_forget() self.graph_area.canvas.draw() self.graph_area.canvas.get_tk_widget().pack(side='top', fill=tk.BOTH, expand=1) def update_data(self, x_data, y_data, _raw_y_data=None): if self.params['user_sets_labels_after_run']: self.data.add_data(x_data, y_data, _raw_y_data) self.display_data() toplevel.UserSetDataLabel(self) else: self.data.add_data(x_data, y_data, _raw_y_data) self.display_data() def change_label(self, label, index=None): if not index: index = self.data.index - 1 self.data.change_label(label, index) self.update_legend() def add_notes(self, _notes): self.data.notes[-1] = _notes def display_data_user_input(self, x_data, y_data): label = self.label_instance self.display_data(x_data, y_data, self.data.index-1) def display_data(self): """ Take in a x and y data set and plot them in the self instance of the pyplot :param x_data: x axis data :param y_data: y axis data :return: """ index = self.data.index - 1 # it was incremented at the end of the add_data method x_data = self.data.x_data[index] y_data = self.data.y_data[index] _label = self.data.label[index] """ if this is the first data series to be added the legend has to be displayed also """ if not self.legend_displayed: _box = self.graph_area.axis.get_position() self.graph_area.axis.set_position([_box.x0, _box.y0, _box.width * legend_space_ratio, _box.height]) self.legend_displayed = True """ add the data to the plot area and update the legend """ l = self.graph_area.axis.plot(x_data, y_data, label=_label) self.data.colors.append(l[0].get_color()) self.plotted_lines.append(l) self.update_legend() def update_legend(self): handle, labels = self.graph_area.axis.get_legend_handles_labels() self.graph_area.axis.legend(handle, self.data.label, loc='center left', bbox_to_anchor=(1, 0.5), title='Data series', prop={'size': 10}, fancybox=True) # not adding all this screws it up for some reason # self.graph_area.axis.legend.get_frame().set_alpha(0.5) self.graph_area.canvas.show() # update the canvas where the data is being shown def delete_all_lines(self): logging.debug("deleting all lines") while self.plotted_lines: l = self.plotted_lines.pop(0) l.pop().remove() # self.plotted_lines is a list of list so you have to pop twice del l # see stackoverflow "how to remove lines in a matplotlib", this is needed to release the memory """ Update the legend with an empty data set but will keep the title and box showing in the graph area """ self.update_legend() def delete_a_line(self, index): logging.debug("deleting line: %i", index) line = self.plotted_lines.pop(index) self.data.remove_data(index) line.pop().remove() del line self.update_legend() def change_line_color(self, _color, index): logging.debug("change line color: ", _color, index) print self.plotted_lines print self.plotted_lines[index] self.plotted_lines[index][0].set_color(_color) self.data.colors[index] = _color def update_graph(self): self.graph_area.canvas.show() def toolbar_toggle(self): """ Display or remove the toolbar from the GUI :return: """ if self.toolbar_status: # there is a toolbar, so remove it self.toolbar.pack_forget() self.toolbar_status = False else: # no toolbar yet so add one self.toolbar.pack(side='left', anchor='w') self.toolbar_status = True def legend_handler(self, event): """ :param event: :return: """ if event.x > (0.8 * self.winfo_width()): # if mouse is clicked on the right side print "on right side" legend_top.DataLegendTop(self) def resize_x(self, x_low, x_high): """ Change the scale of the x axis :param x_low: lower limit on x axis :param x_high: upper limit on x axis :return: """ self.graph_area.axis.set_xlim([x_low, x_high]) self.graph_area.canvas.show() def resize_y(self, _current_limit): """ Change the scale of the y axis :param _current_limit: most current (positive or negative) :return: """ self.graph_area.axis.set_ylim(-_current_limit, _current_limit) self.graph_area.canvas.show()