简体   繁体   English

在 Tkinter GUI 中显示 Matplotlib 音频图

[英]Display Matplotlib Audio Graph Inside Tkinter GUI

I was trying to insert a plot graph I get from an audio file into my tkinter root window however I'm not sure how to do it or which widget to use to display.我试图将我从音频文件中获取的绘图图插入到我的 tkinter 根窗口中,但是我不知道该怎么做或使用哪个小部件来显示。

import matplotlib.pyplot as plt
import scipy.io.wavfile
from tkinter import *

root = Tk()
root.geometry("700x400")
root.title("SOUNDART")
root.resizable(False, False)
root.configure(bg="#1d1d1d")

rate, data = scipy.io.wavfile.read("example.wav")
plt.plot(data)

root.mainloop()

here is a complete example.这是一个完整的例子。

You must use canvas to embed the chart and above all use an object-oriented approach.您必须使用画布来嵌入图表,最重要的是使用面向对象的方法。

Audio file is in the same dir of the script.音频文件位于脚本的同一目录中。

#!/usr/bin/python3
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox

import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

try:
    from matplotlib.backends.backend_tkagg import NavigationToolbar2Tk as nav_tool
except:
    from matplotlib.backends.backend_tkagg import  NavigationToolbar2TkAgg as nav_tool
from matplotlib.figure import Figure
from matplotlib import gridspec

from scipy.io import wavfile
import numpy as np

class App(tk.Tk):
    def __init__(self):
        super().__init__()

        self.protocol("WM_DELETE_WINDOW", self.on_exit)
        #self.geometry("700x400")
        self.title("SOUNDART")
        self.init_ui()
        self.set_plot()
       
    def init_ui(self):

        f = ttk.Frame(padding = 8)
        fig = Figure()
        fig.subplots_adjust(bottom=0.10, right=0.96, left=0.08, top=0.95, wspace=0.10)
        self.plt = fig.add_subplot(111, facecolor=('xkcd:light grey'))
        canvas = FigureCanvasTkAgg(fig, f)
        toolbar = nav_tool(canvas, f)
        toolbar.update()
        canvas._tkcanvas.pack(fill=tk.BOTH, expand=1)

        f.pack(fill=tk.BOTH, expand=1)

    def set_plot(self):

        
        fig = plt.figure(figsize=(8, 8))

        my_file = 'example.wav'

        samplerate, data = wavfile.read(my_file)

        length = data.shape[0] / samplerate

        samplerate, data = wavfile.read(my_file)

        time = np.linspace(0., length, data.shape[0])

        self.plt.plot(time, data[:, 0], label="Left channel")

        self.plt.plot(time, data[:, 1], label="Right channel")

        self.plt.legend()

        self.plt.set_xlabel("Time [s]")

        self.plt.set_ylabel("Amplitude")

    def on_exit(self):
        if messagebox.askokcancel(self.title(), "Do you want to quit?", parent=self):
            self.destroy()               
    
if __name__ == '__main__':
    app = App()
    app.mainloop()

在此处输入图片说明

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

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