qing
qing

Reputation: 11

Closing tkinter windows doesn't kill the python program when using matplotlib to plot graph

I am currently working on a GUI using python tkinter and matplotlib. However, after adding the matplotlib features to my GUI, I couldn't kill the program by closing all the windows anymore. I was able to do that previously when I experimented with some simple matplotlib plots. I would really appreciate if anyone could help me by giving some suggestions to try. Thank you! Here is the code that is relevant to my problem:

import tkinter as tk
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.backend_bases import MouseEvent, key_press_handler
import sys
sys.path.append('/Users/YangQing/Desktop/eMPRess')
import empress

class App:
def plot_cost_landscape(self):
        """Plots the cost landscape using matplotlib and embeds the graph in a tkinter window."""    
        # creates a new tkinter window 
        plt_window = tk.Toplevel(self.master)
        plt_window.geometry("550x550")
        plt_window.title("Matplotlib Graph DEMO")
        # creates a new frame
        plt_frame = tk.Frame(plt_window)
        plt_frame.pack(fill=tk.BOTH, expand=1)
        plt_frame.pack_propagate(False)
        recon_input = empress.read_input("./examples/heliconius.newick")
        cost_region = empress.compute_cost_region(recon_input, 0.5, 10, 0.5, 10)  # create
        cost_region.draw_to_file('./examples/cost_poly.png')  # draw to a file
        fig = cost_region.draw()  # draw to figure (creates matplotlib figure)

        canvas = FigureCanvasTkAgg(fig, plt_frame)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        toolbar = NavigationToolbar2Tk(canvas, plt_frame)
        toolbar.update()
        canvas.get_tk_widget().pack(side=tk.TOP)
        # prints the x,y coordinates clicked by the user inside the graph otherwise prints an error message
        fig.canvas.callbacks.connect('button_press_event', self.get_xy_coordinates)

Upvotes: 1

Views: 82

Answers (1)

Sobhan Bose
Sobhan Bose

Reputation: 134

Try adding os._exit(0) at the end of the script!! For this you also need to import the os module into your script.
os._exit() method in Python is used to exit the process with specified status.

Upvotes: 2

Related Questions