简体   繁体   English

tkinter中带有matplotlib图的弹出窗口

[英]popup windows with matplotlib figure in tkinter

When I insert a matplotlib figure in my tkinter window, when I start my program, extra popup windows appear. 当我在tkinter窗口中插入matplotlib图形时,当我启动程序时,会出现额外的弹出窗口。 They do not affect the functionality of my GUI, but they are a bit annoying. 它们不会影响我的GUI的功能,但是有点烦人。

I have written a basic script that shows the problem. 我写了一个基本的脚本来显示问题。 I run this through Spyder: 我通过Spyder运行:

import tkinter as tk
import matplotlib
matplotlib.use("TkAgg")

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.pyplot import figure as Figure
from matplotlib import pyplot as plt

class MyGUI(tk.Tk):
    def __init__(self,master):
        self.f=Figure(figsize=(5,5),dpi=100)
        self.fig, self.ax= plt.subplots()

        self.canvas = FigureCanvasTkAgg(self.fig,master)


        self.toolbar=NavigationToolbar2Tk(self.canvas,master)
        #self.toolbar.update()
        self.canvas._tkcanvas.pack(padx=20, pady=20)

root =tk.Tk()
window=MyGUI(root)
root.mainloop()

When I run this, I get three windows. 当我运行它时,我得到三个窗口。 One is the root window that shows an empty graph and a toolbar (labeled 'tk'). 一个是显示空图和工具栏(标记为“ tk”)的根窗口。 This is the only window that I want. 这是我想要的唯一窗口。 Then I get a 'Figure 1' window with a toolbar and a 'Figure 2' window with a graph and toolbar. 然后我得到一个带有工具栏的“图1”窗口和一个带有图形和工具栏的“图2”窗口。 运行演示代码时的输出

From commenting out the second half of the init method, it looks like the problem comes from this part. 通过注释掉init方法的后半部分,看来问题出在这部分。

self.f=Figure(figsize=(5,5),dpi=100)
self.fig, self.ax= plt.subplots()

self.canvas = FigureCanvasTkAgg(self.fig,master)

However, I am quite new to object oriented programming and tkinter, and therefore not experienced enough to figure out what the mistake is. 但是,我对面向对象的编程和tkinter还是很陌生,因此经验不足,无法弄清错误是什么。 Any ideas? 有任何想法吗?

You are creating two figures. 您正在创建两个图形。 One of them is created via pyplot . 其中之一是通过pyplot创建的。 One shouldn't try to embedd a pyplot figure inside a custom GUI. 不应尝试将pyplot图形嵌入到自定义GUI中。 Remove pyplot completely and create only a single figure. 完全删除pyplot并仅创建一个图形。

import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure

class MyGUI(tk.Tk):
    def __init__(self,master):
        self.fig=Figure(figsize=(5,5),dpi=100)
        self.ax = self.fig.add_subplot(111)

        self.canvas = FigureCanvasTkAgg(self.fig,master)

        self.toolbar=NavigationToolbar2Tk(self.canvas,master)
        #self.toolbar.update()
        self.canvas._tkcanvas.pack(padx=20, pady=20)

root =tk.Tk()
window=MyGUI(root)
root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM