【发布时间】:2019-12-13 17:41:09
【问题描述】:
我正在编写 ACP 代码,在我的代码中,我有很多图表(来自 matplotlib),我不想显示刚刚保存的图表,希望有一个必须在 tkinter 界面中。但是,这不起作用。
我已尝试将其保存为 PNG。然后,对于 tkinter,它应该很容易,因为我只需要显示图像。但是,如果我运行我的代码,它只会显示一个灰色的大方块。我已经尝试过 FigureCanvasTkAgg,它可以工作,但图表没有每个点、烤架、标题的标签......
def ACP():
.....
df = pd.DataFrame({
'x': x,
'y':VaPtri,
'group': Variance
})
sns.regplot(data=df, x="x", y="y", fit_reg=False, marker="+", color="skyblue")
# basic plot
p1=sns.regplot(data=df, x="x", y="y", fit_reg=False, marker="o", color="skyblue")
# add annotations one by one with a loop
for line in range(0,df.shape[0]):
p1.text(df.x[line]+0.1, df.y[line], df.group[line], horizontalalignment='left', size='medium', color='black', weight='semibold')
plt.grid()
plt.xlabel('Numero de valeur propre')
plt.ylabel('Valeur propre')
plt.title('Variance accumulé')
plt.savefig(nom+'variance'+'.png')
plt.plot(x,VaPtri)
image = Image.open(nom+'variance'+'.png')
photo = ImageTk.PhotoImage(image)
largeur = photo.width() # dimensions en nombre de pixels
hauteur = photo.height()
zone_image = Canvas(Mafenetre, width = largeur, height = hauteur) # crée un canevas de dimensions ajustées à celles de l'image
zone_image.create_image(0,0, anchor = NW, image = photo) # association image/widget
zone_image.grid(column=0,row=10) # placement du widget
return
def graphique():....return
##interface
Mafenetre = Tk()
Mafenetre.title("ACP")
Mafenetre.geometry('1200x600')
Mafenetre.configure(bg = "white")
#bouton lancer Graphique
Frame12 = Frame(Mafenetre,borderwidth=2,relief=GROOVE,bg='gold')
Frame12.grid(rowspan=2,column= 2,row=6)
Label(Frame12,text=" Projections",bg='gold').grid(row=6, column=2)
Button(Frame12,text="Lancer",fg='navy',command=Graphique,bg='gold').grid(row=7, column=2)
#bouton lancer ACP
Frame2 = Frame(Mafenetre,borderwidth=2,relief=GROOVE,bg='deep sky blue')
Frame2.grid(rowspan=2,column=2,row=2)
Label(Frame2,text="ACP",bg='deep sky blue').grid(row=2, column=2)
Button(Frame2,text="Lancer",fg='navy',command=ACP,bg='deep sky blue').grid(row=3, column=2)
这不是格式问题。确实,有时图表会起作用,但在非常特殊的时刻。 首先当图形在第二个函数中时。 其次,当我不把 plt.show() 放在一边时(但我需要将它们删除,这样图表就不会出现新的弹出窗口。)如果需要,我可以显示更多代码或图表或界面。
【问题讨论】:
-
如果您询问为什么图片没有显示,请阅读Why does Tkinter image not show up if created in a function?
-
谢谢,通过将照片和图像设置为全局,它现在可以工作了。再次感谢
标签: python user-interface matplotlib tkinter