2

I wrote a short code in order to make a GUI using Tkinter. I want to get some data plotted on a new window by clicking a button. But, when I run the code, I get a plot before even clicking the button. Can any one explain to me (knowing that I am a beginner): 1. Why this occurs that way? 2. How can I fix it?

def stop_draw():
    """
    """
    import tkinter
    from matplotlib.backends.backend_tkagg import ( FigureCanvasTkAgg,                     
        NavigationToolbar2Tk)
    # Implement the default Matplotlib key bindings.
    from matplotlib.backend_bases import key_press_handler
    from matplotlib.figure import Figure
    import numpy as np

    chid_wind = tkinter.Tk()
    chid_wind.wm_title("Embedding in Tk")

    fig = Figure(figsize=(5, 4), dpi=100)
    t = np.arange(0, 3, .01)
    fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))

    canvas = FigureCanvasTkAgg(fig, master=chid_wind)  # A 
    tk.DrawingArea.
    canvas.draw()
    canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, 
    expand=1)

    toolbar = NavigationToolbar2Tk(canvas, chid_wind)
    toolbar.update()
    canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, 
    expand=1)


    def on_key_press(event):
        print("you pressed {}".format(event.key))
        key_press_handler(event, canvas, toolbar)


    canvas.mpl_connect("key_press_event", on_key_press)


    def _quit():
        chid_wind.quit()     # stops mainloop
        chid_wind.destroy()  # this is necessary on Windows to prevent
                # Fatal Python Error: PyEval_RestoreThread: NULL tstate


    button = tkinter.Button(master=chid_wind, text="Quit", command=_quit)
    button.pack(side=tkinter.BOTTOM)

    tkinter.mainloop()

    #..............................................................    

from tkinter import *

window1=Tk()
#........................................
frmmeasurement=Frame(window1, bg="gray")
frmmeasurement.pack(side=LEFT)
#........................................
btnstop=Button(frmmeasurement, text='Stop', width=30,
           font=("Times New Roman", 12, "bold"), command=stop_draw())
btnstop.pack(fill=X)
#........................................

I expect to have one window, containing a frame and a button (named 'stop'); then only when I click this button a new window containig the plot appears.

  • Notice the difference between `command=_quit` and `command=stop_draw()`. One of those specifies a function to be called later (when the button is clicked); the other one calls a function *right now* (and uses the function's return value as the action to be performed later). – jasonharper Aug 20 '19 at 22:29
  • Thank you so much for this useful information. – Slimane Latreche Aug 20 '19 at 23:36

0 Answers0