Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9131001
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T08:04:07+00:00 2026-06-17T08:04:07+00:00

I want to be able to create a plot, press one button or another

  • 0

I want to be able to create a plot, press one button or another depending on what the plot shows, and then plot the following object. However, I am having some trouble wih it: it seems I can’t make it “wait” untill a button is pressed. Also, I am wondering if it would be possible to pass some parameters to the press_event, like a path to save something.

Here is the scheme of the program in case it helps. Thanks a lot in advance!

# event definition
def ontype(event):
    if event.key == '1':
        do stuff 1
        plt.savefig(...)
        plt.clf()
    elif event.key == '2':
        do stuff 2
        plt.savefig(...)
        plt.clf()
    elif event.key == '3':
        do stuff 3
        plt.savefig(...)
        plt.clf()

# main program
...stuff
create figure
plt.show()
plt.gcf().canvas.mpl_connect('key_press_event',ontype)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T08:04:08+00:00Added an answer on June 17, 2026 at 8:04 am

    You must call plt.gcf().canvas.mpl_connect('key_press_event',ontype) before plt.show(). In non-interactive mode, the execution waits at plt.show() until the plot-window is closed.

    import pylab as plt
    
    # event definition
    def ontype(event):
        if event.key == '1':
            print "1"
        elif event.key == '2':
            print "2"
        elif event.key == '3':
            print "3"
    
    # main program
    plt.plot([1,6,3,8,7])
    plt.gcf().canvas.mpl_connect('key_press_event',ontype)
    plt.show()
    

    Alternatively, replace in your sample plt.show() to plt.ion(), which enables interactive mode. But it depends on your specific needs which solution you prefer.

    Edit

    New example using Tkinter

    import random
    import matplotlib
    matplotlib.use('TkAgg')
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
    from matplotlib.figure import Figure
    
    try:
        import Tkinter as Tk
    except ImportError:
        import tkinter as Tk
    import tkMessageBox
    
    class PlotClassifier(Tk.Tk):
        def __init__(self, plot_generator, arguments, classes, classification_callback, *args, **kwargs):
            Tk.Tk.__init__(self, *args, **kwargs)
            self.title("Plot classifier, working on %i plots" % len(arguments))
            #self.label = Tk.Label(text="Plot classifier, working on %i plots" % len(arguments))
            #self.label.pack(padx=10, pady=10)
            self._plot_generator = plot_generator
            self._arguments = arguments
            self._classes = [str(x) for x in classes]
            self._classification_callback = classification_callback
            self._setup_gui()
    
        def _setup_gui(self):
            #self.columnconfigure(0, minsize=100, weight=2)
            #self.columnconfigure(1, minsize=500, weight=8)
            f = Figure()
            self._ax = f.add_subplot(111)
            buttons_frame = Tk.Frame(self)
            buttons_frame.pack(side=Tk.TOP, fill=Tk.BOTH, expand=True)
            buttons_class = []
            for i, cls in enumerate(self._classes):
                buttons_class.append(Tk.Button(master=buttons_frame, text=cls, 
                                               command=lambda x=i: self.button_classification_callback(self._current_args, x)))
                buttons_class[-1].pack(side=Tk.LEFT)
            button_quit = Tk.Button(master=buttons_frame, text='Quit', command=self.destroy)
            button_quit.pack(side=Tk.RIGHT) #.grid(row=0,column=0)
    
            self._canvas = FigureCanvasTkAgg(f, master=self)
            self._canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) #.grid(row=0, column=1, rowspan=3) #
            self._canvas.show()
    
            toolbar = NavigationToolbar2TkAgg( self._canvas, self )
            toolbar.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) #.grid(row=3, column=1) #
            toolbar.update()
    
        def button_classification_callback(self, args, class_idx):
            self._classification_callback(args, self._classes[class_idx])
            self.classify_next_plot()
    
        def classify_next_plot(self):
            try:
                self._current_args = self._arguments.pop(0)
                self._ax.cla()
                self._plot_generator(self._ax, *self._current_args)
                self._canvas.draw()
            except IndexError:
                tkMessageBox.showinfo("Complete!", "All plots were classified")
                self.destroy()        
    
    def create_plot(ax, factor):
        ax.plot([(i*factor) % 11 for i in range(100)])
    
    def announce_classification(arguments, class_):
        print arguments, class_
    
    if __name__ == "__main__":
        classes = ["Class %i"%i for i in range(1, 6)]
        arguments_for_plot = [[random.randint(1,10)] for x in range(10)]
        root = PlotClassifier(create_plot, arguments_for_plot, classes, classification_callback=announce_classification)
        root.after(50, root.classify_next_plot)
        root.mainloop()
    

    The class takes as arguments:
    * a callback to create each plot
    * a list of lists of arguments for each plot to generate (might each be an empty list)
    * a list of class-names. For each class, a button is created
    * a callback that is called each time a classification has been performed

    Any feedback would be appreciated.

    *EDIT 2 *
    For your comment, a slightly modified version. For every iteration of the loop, a new window is opened

    import random
    import matplotlib
    matplotlib.use('TkAgg')
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
    from matplotlib.figure import Figure
    
    try:
        import Tkinter as Tk
    except ImportError:
        import tkinter as Tk
    import tkMessageBox
    
    class PlotClassifier(Tk.Tk):
        def __init__(self, plot_generator, arguments, classes, *args, **kwargs):
            Tk.Tk.__init__(self, *args, **kwargs)
            self.title("Plot classifier")
            self._plot_generator = plot_generator
            self._arguments = arguments
            self._classes = [str(x) for x in classes]
            self.class_ = None
            self._setup_gui()
    
        def _setup_gui(self):
            #self.columnconfigure(0, minsize=100, weight=2)
            #self.columnconfigure(1, minsize=500, weight=8)
            f = Figure()
            self._ax = f.add_subplot(111)
            buttons_frame = Tk.Frame(self)
            buttons_frame.pack(side=Tk.TOP, fill=Tk.X, expand=True)
            buttons_class = []
            for i, cls in enumerate(self._classes):
                buttons_class.append(Tk.Button(master=buttons_frame, text=cls, 
                                               command=lambda x=i: self.button_classification_callback(x)))
                buttons_class[-1].pack(side=Tk.LEFT)
            button_quit = Tk.Button(master=buttons_frame, text='Quit', command=self.destroy)
            button_quit.pack(side=Tk.RIGHT) #.grid(row=0,column=0)
    
            self._canvas = FigureCanvasTkAgg(f, master=self)
            self._canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) #.grid(row=0, column=1, rowspan=3) #
            self._canvas.show()
    
            toolbar = NavigationToolbar2TkAgg( self._canvas, self )
            toolbar.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) #.grid(row=3, column=1) #
            toolbar.update()
    
        def button_classification_callback(self, class_idx):
            self.class_ = self._classes[class_idx]
            self.destroy()
    
        def classify_plot(self):
            self._ax.cla()
            self._plot_generator(self._ax, *self._arguments)
            self._canvas.draw()
            self.mainloop()
            return self.class_
    
    def create_plot(ax, factor):
        ax.plot([(i*factor) % 11 for i in range(100)])
    
    
    if __name__ == "__main__":
        classes = ["Class %i"%i for i in range(1, 6)]
        arguments_for_plot = [[random.randint(1,10)] for x in range(10)]
        for args in arguments_for_plot:
            classifier = PlotClassifier(create_plot, args, classes)
            class_ = classifier.classify_plot()
            print args, class_
            if class_ is None:
                break
    

    This helps to fit into your own for-loop, but you still have to give a function to do the plotting after the GUI was created.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to be able to create a file from the Content Provider, however
I am running Octave 3.4.0 and want to create a transparent surface plot. However,
I want to be able to create an instance of the DataContext object for
I want to be able to create a Pandas DataFrame with MultiIndexes for the
I want to be able to create links looking like buttons with dynamic text
I want to be able to create modal dialogs, with, for example close: function()
I want to be able to create a temporary text File in Java to
I want to be able to create the XSD file for my typed dataset
I want to be able to create a KPI List on my MOSS 2007
hey i want to be able to create multiple shapes and store them perhaps

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.