【问题标题】:Closing tkinter windows doesn't kill the python program when using matplotlib to plot graph使用 matplotlib 绘制图形时,关闭 tkinter 窗口不会杀死 python 程序
【发布时间】:2020-06-07 14:03:41
【问题描述】:

我目前正在使用 python tkinter 和 matplotlib 开发 GUI。但是,将 matplotlib 功能添加到我的 GUI 后,我无法再通过关闭所有窗口来终止程序。当我尝试一些简单的 matplotlib 图时,我之前能够做到这一点。如果有人可以通过提供一些尝试的建议来帮助我,我将不胜感激。谢谢!这是与我的问题相关的代码:

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)

【问题讨论】:

  • 我遇到了同样的麻烦,只需在代码末尾添加这行 os._exit(0)

标签: python matplotlib tkinter


【解决方案1】:

尝试在脚本末尾添加os._exit(0)!!为此,您还需要将 os 模块导入到您的脚本中。
Python 中的os._exit() 方法用于以指定状态退出进程。

【讨论】:

    猜你喜欢
    • 2015-08-09
    • 1970-01-01
    • 2018-05-18
    • 2019-01-04
    • 2014-11-04
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多