【问题标题】:Embedding matplotlib into tkinter canvas opens two windows将 matplotlib 嵌入 tkinter 画布会打开两个窗口
【发布时间】:2018-03-06 00:12:17
【问题描述】:

我正在编写的以下代码没有按照我希望的方式运行。我已将 matplotlib 图嵌入到 tkinter 画布中。该程序打开了两个窗口,其中一个正常运行,另一个没有必要。我不知道如何解决这个问题。这是代码,请忽略不必要的导入:)

import numpy as np
import sys
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib as mpl
from matplotlib import cm
from numpy.random import random
from matplotlib.widgets import Button
import matplotlib.colors
import tkinter as tk
import matplotlib.backends.tkagg as tkagg
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

DEBUG_MODE = False                          #Debug mode - True = ON
MATRIX_WIDTH = 50
MATRIX_HEIGHT = 50
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
LED_COUNT = MATRIX_WIDTH * MATRIX_HEIGHT
REFRESH_RATE = 30                           #REFRESH_RATE used to control FuncAnimation interval
MATRIX = random((50,50))                    #Fills MATRIX as not to be null for first print  


plt.rcParams['toolbar'] = 'None'            #Disables matplotlib toolbar
fig = plt.figure(figsize=(3,3))             #'figsize' measured in inches
im = plt.imshow(MATRIX, interpolation='nearest', cmap=cm.Spectral)
plt.axis('off')                             #Turns off x, y axis

def data_gen():                             #Generates amd populates MATRIX with pattern data
    while True:        
        MATRIX = random((MATRIX_WIDTH, MATRIX_HEIGHT))
        yield MATRIX
        if (DEBUG_MODE): print("MATRIX yeilded")

def update(data):                           #Updates/prints new MATRIX from data_gen()
    im.set_array(data)
    if (DEBUG_MODE): print("Updated data")



root = tk.Tk()
label = tk.Label(root,text="Matrix Program").grid(column=0, row=0)
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().grid(column=0,row=1)


ani = animation.FuncAnimation(fig, update, data_gen, interval=REFRESH_RATE)
plt.show()

需要对这段代码做些什么,以便它只从 tkinter 打开一个嵌入了实时 matplotlib 图形的画布?

如何设置画布的大小?

【问题讨论】:

    标签: python user-interface matplotlib canvas tkinter


    【解决方案1】:

    如果您想在 tk GUI 中显示您的图形,请不要调用 plt.show()。嵌入时最好不要使用pyplot

    另一方面,您可能想在某个时候启动主循环tk.mainloop()

    请参阅matplotlib example,了解如何将 matplotlib 图嵌入 tk。

    【讨论】:

    • 谢谢!如果您建议完全不使用 pyplot 进行嵌入,您会建议什么来获得相同的结果?
    • 你读过这个例子吗?它也不使用 pyplot 。如果你甚至不导入 pyplot,你就不会在尝试使用它时遇到问题。
    • 另外,关于在这种情况下如何设置画布大小的任何指针?
    • 画布大小由图形大小决定。
    • 如果我想要图形在画布的中心并且图形周围有 100 像素的空间怎么办?
    猜你喜欢
    • 2018-11-17
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 2021-12-27
    相关资源
    最近更新 更多