Python Tkinter中的内存溢出和子批行为

Python Tkinter中的内存溢出和子批行为,python,image,matplotlib,tkinter,Python,Image,Matplotlib,Tkinter,我试图制作一个由6个饼图组成的图,每个饼图都有嵌入的图像。我已经能够制作饼图和子图(空)。但是,我不理解在右下角生成所有图形的行为。(目前是这样)。另外,当我运行6个图形时,我得到一个内存错误。(当我运行两个图表时不会发生这种情况) Tkinter回调中出现异常: 记忆者 我包括我的代码,有足够的数据行生成两个图表。缺少的5个png文件可以通过绘制和保存实体块png文件轻松构建 我也意识到这里有两个问题,但因为它们都来自同一个代码,所以我想问一下这两个问题 所以 1) 我怎样才能让子图在它们自己

我试图制作一个由6个饼图组成的图,每个饼图都有嵌入的图像。我已经能够制作饼图和子图(空)。但是,我不理解在右下角生成所有图形的行为。(目前是这样)。另外,当我运行6个图形时,我得到一个内存错误。(当我运行两个图表时不会发生这种情况)

Tkinter回调中出现异常:

记忆者

我包括我的代码,有足够的数据行生成两个图表。缺少的5个png文件可以通过绘制和保存实体块png文件轻松构建

我也意识到这里有两个问题,但因为它们都来自同一个代码,所以我想问一下这两个问题

所以 1) 我怎样才能让子图在它们自己的位置上分布饼图呢。似乎也帮不了我

2) 如何避免出现内存错误(我可能打开了一些东西,不知道如何关闭它,但不知道是什么或如何关闭),这似乎有类似的问题,但我无法理解它是如何修复的

import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import sys
import scipy.stats

#import panda as pd
import numpy as np

size_distribution = np.array([
    [ 1 , 1 , 0.48 , 0.42 , 0.10 ],
    [ 1 , 1 , 0.52 , 0.38 , 0.10 ],
    [ 2 , 2 , 0.38 , 0.42 , 0.20 ],
    [ 2 , 2 , 0.42 , 0.38 , 0.20 ]])

def name_of_files(): # files named as such in directory with python script
    Variety = np.array(['_A_', '_B_']) #Variety of tested stuff
    Treatment = np.array(['_1_', '_2_', '_3_']) # Treatment of stuff
    Cut = np.array(['_i_', '_ii_']) # Cut of stuff
    return Variety, Treatment, Cut

def label(): # provides info on labelling in pie chart
    var = np.array(['A_', 'B_'])
    treat = np.array(['1_', '2_', '3_'])
    return var, treat

def size(xx, strt, end): #produces individual pie chart with plt.show() or sends wedges to main
    Variety, Treatment, Cut = name_of_files()
    var, treat = label()
    long = int(len(size_distribution))
    count = int(strt)
    cut = int(0)
    while count < (long - 1) and count < end:
        coarse = np.mean([xx[count][2], xx[count+1][2]])
        fine = np.mean([xx[count][3], xx[count+1][3]])
        residue = np.mean([xx[count][4], xx[count+1][4]])
        name = (str(Variety[int(xx[count][0])-1]) +
                str(Treatment[int(xx[count][1])-1]) +
                str(Cut[int(cut)]) +
                '.png')
        #print(name, cut)
        if cut == 0:
            name_coarse = name
            label_coarse = (str(var[int(xx[count][0])-1]) + '\n' +
                            str(treat[int(xx[count][1])-1]) + '\n' +
                            'coarse fraction:\n' + str(np.around(coarse, 3)*100) + '%')
            #print(label_coarse, coarse)
            cut = int(1)
        elif cut == 1:
            name_fine = name
            label_fine = (str(var[int(xx[count][0])-1]) + '\n' +
                            str(treat[int(xx[count][1])-1]) + '\n' +
                            'fine fraction:\n' + str(np.around(fine, 3)*100) + '%')
            label_residue = ('\n\n' + str(var[int(xx[count][0])-1]) + ', ' +
                            str(treat[int(xx[count][1])-1]) + '\n' +
                            'residue fraction: ' + str(np.around(residue, 3)*100) + '%')
            #print(label_fine, fine)
            #print(label_residue, residue)
            #print('\t\t\t\t', fine+coarse+residue)
            cut = int(0)
            #print('\n\n\t\t\tcount = ', count)
            count += 2
            #print('\n\n\t\t\tcount = ', count)


            file_index = np.array([name_coarse, 'Black.png', name_fine])
            labels = np.array([label_coarse, label_residue, label_fine])
            total = [coarse, residue, fine]
            plt.gca().axis('equal')
            wedges, texts = plt.pie(total, startangle=90, labels=labels,
                        wedgeprops = { 'linewidth': 3, "edgecolor" :"k",
                                       "fill":False,  })
            positions = [(-1,0.3),(0,-0.5),(0.5,0.5)]
            zooms = [0.4,0.4,0.4]
            for i in range(3):
                #print('\ti = ', i)
                fn = str(file_index[i]).format(labels[i].lower(), fontsize=20)
                img_to_pie(fn, wedges[i], xy=positions[i], zoom=zooms[i] )
                wedges[i].set_zorder(10)
            #plt.show() #shows the pie chart nicely
            #plt.close('all')
            #print('Wedges type: ',type(wedges),'\nLength: ', len(wedges))
            #print('Texts type: ',type(wedges),'\nTexts: ', len(wedges))
            #print(type(texts), len(texts))
            #print(locals())
    return wedges

def img_to_pie( fn, wedge, xy, zoom=1, ax = None):
    if ax==None: ax=plt.gca()
    im = plt.imread(fn, format='png')
    path = wedge.get_path()
    patch = PathPatch(path, facecolor='none')
    plt.gca().add_patch(patch)
    imagebox = OffsetImage(im, zoom=zoom, clip_path=patch, zorder=-10)
    ab = AnnotationBbox(imagebox, xy, xycoords='data', pad=0, frameon=False)
    ax.add_artist(ab)
    return ()

def main():
    fig = plt.figure()
    ho = fig.add_subplot(1, 2, 1)
    hm = fig.add_subplot(1, 2, 2)
    '''
    f, ((ho , hm, hs), (mo, mm, ms)) = (
        plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True,
                 squeeze=False, subplot_kw=None, gridspec_kw=None))
    #plt.show() # six empty plots as expected'''
    j = [ho, hm]#, hs]#, mo, mm, ms]
    x = [0, 2]#, 4]#, 6, 8, 10]
    count = 0
    int(count)
    while count < len(x):
        j[count] = size(size_distribution, x[count], x[count]+2)
        print(x[count], '\n', j[count])
        count += 1
    print(ho, '\n', hm)
    plt.show()  

main()
导入matplotlib.pyplot作为plt
从matplotlib.patches导入PathPatch
从matplotlib.offsetbox导入OffsetImage、AnnotationBbox
导入系统
导入scipy.stats
#作为pd导入熊猫
将numpy作为np导入
大小\分布=np.array([
[ 1 , 1 , 0.48 , 0.42 , 0.10 ],
[ 1 , 1 , 0.52 , 0.38 , 0.10 ],
[ 2 , 2 , 0.38 , 0.42 , 0.20 ],
[ 2 , 2 , 0.42 , 0.38 , 0.20 ]])
def name_of_files():#使用python脚本在目录中按此命名的文件
Variety=np.数组([''u A',''u B'])各种各样的被测试的东西
处理=np.数组([''1'',''2'',''3'])处理内容
Cut=np.array([''i'',''ii'])切块
返回品种、处理、切割
def label():#在饼图中提供有关标签的信息
var=np.array(['A\','B\']))
treat=np.array(['1','2','3')
返回变量,处理
def大小(xx、strt、end):#使用plt.show()生成单独的饼图或将楔块发送到main
种类、处理、切割=文件名称()
var,treat=label()
长=整数(长(大小分布))
计数=整数(strt)
切割=整数(0)
当计数<(长-1)和计数<结束时:
粗略=np.平均值([xx[计数][2],xx[计数+1][2])
精细度=np.平均值([xx[计数][3],xx[计数+1][3])
剩余值=np.平均值([xx[计数][4],xx[计数+1][4])
name=(str(variation[int(xx[count][0])-1])+
str(治疗[int(xx[计数][1])-1])+
str(切割[int(切割)])+
“.png”)
#打印(名称、剪切)
如果切割=0:
name_=name
label_rough=(str(var[int(xx[count][0])-1])+'\n'+
str(treat[int(xx[count][1])-1])+'\n'+
'粗分数:\n'+str(np.around(粗分数,3)*100)+'%')
#打印(标签粗、粗)
切割=整型(1)
elif cut==1:
name\u fine=name
label_fine=(str(var[int(xx[count][0])-1])+'\n'+
str(treat[int(xx[count][1])-1])+'\n'+
'精细分数:\n'+str(np.环绕(精细,3)*100)+'%')
标签_剩余=('\n\n'+str(var[int(xx[count][0])-1])+,'+
str(treat[int(xx[count][1])-1])+'\n'+
'残基分数:'+str(np.around(残基,3)*100)+'%')
#打印(标签_精细,精细)
#打印(标签_残留物,残留物)
#打印('\t\t\t\t',细+粗+残)
切割=整数(0)
#打印('\n\n\t\t\t计数=',计数)
计数+=2
#打印('\n\n\t\t\t计数=',计数)
file\u index=np.array([name\u粗略,'Black.png',name\u精细])
labels=np.array([label\u粗略,label\u剩余,label\u精细])
总计=[粗、残、细]
plt.gca().axis('equal')
楔子,文本=plt.pie(总计,startangle=90,标签=labels,
wedgeprops={'linewidth':3,“edgecolor”:“k”,
“填充”:False,})
位置=[(-1,0.3)、(0,-0.5)、(0.5,0.5)]
缩放=[0.4,0.4,0.4]
对于范围(3)中的i:
#打印('\ti=',i)
fn=str(文件索引[i])。格式(标签[i].lower(),fontsize=20)
img_到pie(fn,楔形[i],xy=位置[i],缩放=缩放[i])
楔子[i].集合顺序(10)
#plt.show()#很好地显示了饼图
#plt.close(“全部”)
#打印('楔形类型:',类型(楔形),'\n长度:',长度(楔形))
#打印('文本类型:',类型(楔形),'\n文本:',长度(楔形))
#打印(字体(文本)、透镜(文本))
#打印(局部变量())
返回楔
def img_至_饼图(fn、楔形、xy、缩放=1、ax=无):
如果ax==None:ax=plt.gca()
im=plt.imread(fn,format='png')
path=wedge.get_path()
patch=PathPatch(路径,facecolor='none')
plt.gca().add_补丁(补丁)
imagebox=OffsetImage(im,zoom=zoom,clip\u path=patch,zorder=-10)
ab=AnnotationBbox(imagebox,xy,xycoords='data',pad=0,frameon=False)
ax.添加艺术家(ab)
返回()
def main():
图=plt.图()
ho=图添加_子批次(1,2,1)
hm=图添加_子批次(1,2,2)
'''
f、 ((ho,hm,hs),(mo,mm,ms))=(
plt.子批次(nrows=2,ncols=3,sharex=True,sharey=True,
挤压=假,子批次(千瓦=无,网格规格(千瓦=无))
#plt.show()#预期的六个空绘图“”'
j=[ho,hm]#,hs]#,mo,mm,ms]
x=[0,2]#,4]#,6,8,10]
计数=0
整数(计数)
当计数小于len(x)时:
j[count]=大小(大小分布,x[count],x[count]+2)
打印(x[计数],'\n',j[计数])
计数+=1
打印(ho,'\n',hm)
plt.show()
main()

首先,我在回答中为您编写的函数接受一个参数
ax
whic
f, ax_arr = plt.subplots(nrows=2, ncols=3)
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import scipy.stats
import numpy as np

size_distribution = np.array([
    [ 1 , 1 , 0.48 , 0.42 , 0.10 ],
    [ 1 , 1 , 0.52 , 0.38 , 0.10 ],
    [ 2 , 2 , 0.38 , 0.42 , 0.20 ],
    [ 2 , 2 , 0.42 , 0.38 , 0.20 ]])

def name_of_files(): # files named as such in directory with python script
    Variety = np.array(['_A_', '_B_']) #Variety of tested stuff
    Treatment = np.array(['_1_', '_2_', '_3_']) # Treatment of stuff
    Cut = np.array(['_i_', '_ii_']) # Cut of stuff
    return Variety, Treatment, Cut

def label(): # provides info on labelling in pie chart
    var = np.array(['A_', 'B_'])
    treat = np.array(['1_', '2_', '3_'])
    return var, treat

filenames=["data/blueberries.png", "data/blackberries.png","data/raspberries.png"]

def size(xx, strt, end, ax=None): #produces individual pie chart with plt.show() or sends wedges to main
    if not ax: ax=plt.gca()
    Variety, Treatment, Cut = name_of_files()
    var, treat = label()
    long = int(len(size_distribution))
    count = int(strt)
    cut = int(0)
    while count < (long - 1) and count < end:
        coarse = np.mean([xx[count][2], xx[count+1][2]])
        fine = np.mean([xx[count][3], xx[count+1][3]])
        residue = np.mean([xx[count][4], xx[count+1][4]])
        name = (str(Variety[int(xx[count][0])-1]) +
                str(Treatment[int(xx[count][1])-1]) +
                str(Cut[int(cut)]) +
                '.png')

        if cut == 0:
            name_coarse = name
            label_coarse = (str(var[int(xx[count][0])-1]) + '\n' +
                            str(treat[int(xx[count][1])-1]) + '\n' +
                            'coarse fraction:\n' + str(np.around(coarse, 3)*100) + '%')

            cut = int(1)
        elif cut == 1:
            name_fine = name
            label_fine = (str(var[int(xx[count][0])-1]) + '\n' +
                            str(treat[int(xx[count][1])-1]) + '\n' +
                            'fine fraction:\n' + str(np.around(fine, 3)*100) + '%')
            label_residue = ('\n\n' + str(var[int(xx[count][0])-1]) + ', ' +
                            str(treat[int(xx[count][1])-1]) + '\n' +
                            'residue fraction: ' + str(np.around(residue, 3)*100) + '%')
            cut = int(0)
            count += 2

            file_index = np.array([name_coarse, 'Black.png', name_fine])
            labels = np.array([label_coarse, label_residue, label_fine])
            total = [coarse, residue, fine]
            ax.axis('equal')
            wedges, texts = ax.pie(total, startangle=90, labels=labels,
                        wedgeprops = { 'linewidth': 3, "edgecolor" :"k",
                                       "fill":False,  })
            positions = [(-1,0.3),(0,-0.5),(0.5,0.5)]
            zooms = [0.4,0.4,0.4]
            for i in range(3):

                #fn = str(file_index[i]).format(labels[i].lower(), fontsize=20)
                fn = filenames[i]
                img_to_pie(fn, wedges[i], xy=positions[i], zoom=zooms[i],ax=ax )
                wedges[i].set_zorder(10)

    return wedges

def img_to_pie( fn, wedge, xy, zoom=1, ax = None):
    if ax==None: ax=plt.gca()
    im = plt.imread(fn, format='png')
    path = wedge.get_path()
    patch = PathPatch(path, facecolor='none')
    ax.add_patch(patch)
    imagebox = OffsetImage(im, zoom=zoom, clip_path=patch, zorder=10)
    ab = AnnotationBbox(imagebox, xy, xycoords='data', pad=0, frameon=False)
    ax.add_artist(ab)
    return ()

def main():

    f, ax_arr = plt.subplots(nrows=2, ncols=3)

    x = [0, 2, 4, 6, 8, 10] 
    count = 0
    for i, ax in zip(x, ax_arr.flatten()):
        wedges = size(size_distribution, x[count], x[count]+2, ax=ax)

    plt.show()  

main()
#fn = str(file_index[i]).format(labels[i].lower(), fontsize=20)