簡體   English   中英

Python Tkinter:在一個小部件中嵌入一個matplotlib圖

[英]Python Tkinter: Embed a matplotlib plot in a widget

我已經搜索過這個,例如Python Tkinter在GUI中嵌入了Matplotlib,但仍然無法弄明白。 基本上我正試圖在玩家窗口內用tkinter制作一個籃球比賽的球員能力的花式圖表

    self.fig = Figure(figsize=(1.5,1.5))
    self.ax = self.fig.add_axes([0.025,0.025,0.95,0.95],polar=True)
    self.plot_widget = FigureCanvasTkAgg(self.fig, master=self.top)
    self.ax.grid(False)

    N = 5
    theta = np.arange(0.0, 2*np.pi, 2*np.pi/N)
    radii = [self.thisPlayer.rebounds,self.thisPlayer.freeThrows,self.thisPlayer.steal,self.thisPlayer.underRim,self.thisPlayer.distance]
    width = [2*np.pi/(N),2*np.pi/(N),2*np.pi/(N),2*np.pi/(N),2*np.pi/(N)]
    bars = pl.bar(0 , 20,width=2*np.pi, linewidth = 0) + pl.bar(theta, radii, width=width, bottom=0.2)

    for r,bar in zip(radii, bars):
        bar.set_facecolor( cm.jet(r/20.))
        bar.set_alpha(0.5)

    self.ax.set_xticklabels([])
    self.ax.set_yticklabels([])
    self.plot_widget.show()
    self.plot_widget.get_tk_widget().pack()

發生的事情是,播放器窗口現在具有情節小部件,但未顯示情節。 另一方面,只繪制未嵌入tkinter的能力就可以了。 對不起我的英語不好。 提前致謝

設置self.ax ,需要調用self.ax.bar ,而不是pl.bar來繪制self.fig中的self.fig 這是一個可運行的例子:

import matplotlib.pyplot as plt
import numpy as np
import Tkinter as tk
import matplotlib.figure as mplfig
import matplotlib.backends.backend_tkagg as tkagg
pi = np.pi


class App(object):
    def __init__(self, master):
        self.master = master
        self.thisPlayer = Bunch(
            rebounds=20.0,
            freeThrows=5.0,
            steal=5.0,
            underRim=10,
            distance=10)
        self.fig = mplfig.Figure(figsize=(1.5, 1.5))
        self.ax = self.fig.add_axes([0.025, 0.025, 0.95, 0.95], polar=True)
        self.canvas = tkagg.FigureCanvasTkAgg(self.fig, master=master)
        self.ax.grid(False)

        N = 5
        theta = np.arange(0.0, 2 * pi, 2 * pi / N)
        radii = [self.thisPlayer.rebounds, self.thisPlayer.freeThrows,
                 self.thisPlayer.steal, self.thisPlayer.underRim,
                 self.thisPlayer.distance]
        width = [2 * pi / (N)] * 5
        bars = (
            # self.ax.bar(0, 20, width=2 * pi, linewidth=0) +
            self.ax.bar(theta, radii, width=width, bottom=0.2))
        cmap = plt.get_cmap('jet')
        for r, bar in zip(radii, bars):
            bar.set_facecolor(cmap(r / 20.))
            bar.set_alpha(0.5)
        self.ax.set_xticklabels([])
        self.ax.set_yticklabels([])
        self.canvas.get_tk_widget().pack()
        self.canvas.draw()


class Bunch(object):
    """
    http://code.activestate.com/recipes/52308
    foo=Bunch(a=1,b=2)
    """
    def __init__(self, **kwds):
        self.__dict__.update(kwds)


def main():
    root = tk.Tk()
    app = App(root)
    tk.mainloop()

if __name__ == '__main__':
    main()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM