tkinter 中带有 matplotlib 图的弹出窗口 [英] popup windows with matplotlib figure in tkinter

查看:90
本文介绍了tkinter 中带有 matplotlib 图的弹出窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在我的 tkinter 窗口中插入一个 matplotlib 图时,当我启动我的程序时,会出现额外的弹出窗口.它们不会影响我的 GUI 的功能,但它们有点烦人.

When I insert a matplotlib figure in my tkinter window, when I start my program, extra popup windows appear. They do not affect the functionality of my GUI, but they are a bit annoying.

我编写了一个基本脚本来显示问题.我通过 Spyder 运行它:

I have written a basic script that shows the problem. I run this through 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()

当我运行这个时,我得到三个窗口.一个是显示空图形和工具栏(标记为tk")的根窗口.这是我唯一想要的窗口.然后我得到一个带有工具栏的图 1"窗口和一个带有图形和工具栏的图 2"窗口.

When I run this, I get three windows. One is the root window that shows an empty graph and a toolbar (labeled '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.

从注释掉init方法的后半部分来看,问题似乎出在这部分.

From commenting out the second half of the init method, it looks like the problem comes from this part.

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

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

但是,我对面向对象编程和 tkinter 还很陌生,因此经验不足,无法弄清楚错误是什么.有什么想法吗?

However, I am quite new to object oriented programming and tkinter, and therefore not experienced enough to figure out what the mistake is. Any ideas?

推荐答案

您正在创建两个图形.其中之一是通过 pyplot 创建的.不应尝试在自定义 GUI 中嵌入 pyplot 图.完全删除 pyplot 并只创建一个图形.

You are creating two figures. One of them is created via pyplot. One shouldn't try to embedd a pyplot figure inside a custom GUI. Remove pyplot completely and create only a single figure.

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()

这篇关于tkinter 中带有 matplotlib 图的弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆