Tkinter 中 matplotlib 图形作为弹出窗口

0 投票
1 回答
3189 浏览
提问于 2025-04-18 07:17

我有一个应用程序,它需要在校准一些数据后显示残差误差。主窗口是一个matplotlib画布,用来展示原始数据和校准后的数据(如下所定义):

# Begins the actual Application 
class App():
    def __init__(self,master):
        self.fig = plt.Figure()
        self.canvas = FigureCanvasTkAgg(self.fig, master = master)
        self.toolbar = NavigationToolbar2TkAgg(self.canvas, root)
        self.canvas.get_tk_widget().pack()
        self.canvas.draw()

我希望将残差误差显示在一个新窗口中,但到目前为止,我只成功让新的图表附加在主窗口的底部(见下图),我不太确定为什么会这样,接下来该怎么做。

enter image description here

我目前用于绘制误差图的代码如下(这个函数是Class App()的一部分):

####################
# WORK IN PROGRESS #
####################
def displayError(self,errors):
    """ This function displays a graph to show the error
    after calibration.
    """
    self.fig = plt.Figure()
    self.canvas = FigureCanvasTkAgg(self.fig, master = root)
    self.canvas.show()
    self.canvas.get_tk_widget().pack()
    x_array = []
    y_array = []
    labels = []
    for counter,i in enumerate(errors):
        x_array.append(counter)
        labels.append(i[0])
        y_array.append(i[2])
    self.axes = self.fig.add_subplot(111)
    self.axes.scatter(x_array,y_array)
        self.axes.tick_params(axis='x',which='both',bottom='off',top='off',labelbottom='off')
    self.axes.set_ylabel('Mass error (ppm)')
    self.axes.hlines(0,x_array[1]-0.5,x_array[-1]+0.5)
    self.axes.set_xlim(x_array[1]-0.5,x_array[-1]+0.5)
    for counter,i in enumerate(errors):
        self.axes.annotate(i[1],(x_array[counter]+0.1,y_array[counter]+0.1))
        self.axes.vlines(x_array[counter],0,y_array[counter],linestyles='dashed')
    #self.canvas.draw()
####################
# WORK IN PROGRESS #
####################

1 个回答

4

我觉得这是因为你的两个 FigureCanvasTkAgg 都用的是同一个 master。你能为第二个图表创建一个新的 tk.Toplevel 吗?也就是说,可以像这样做:

import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np

import tkinter as tk
root = tk.Tk()

x = np.arange(0, 10, 1)
y = np.arange(0, 10, 1)

fig1 = plt.Figure()
canvas1 = FigureCanvasTkAgg(fig1, master=root)
canvas1.show()
canvas1.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1.0)
ax = fig1.add_subplot(111)
ax.plot(x,y)
canvas1.draw()

root2 = tk.Toplevel()
fig2 = plt.Figure()
canvas2 = FigureCanvasTkAgg(fig2, master=root2)
canvas2.show()
canvas2.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1.0)
ax = fig2.add_subplot(111)
ax.plot(x,2*y)
canvas2.draw()

这样第二个窗口就是一个“弹出窗口”。

撰写回答