Как добавить линейный график matplotlib в графический интерфейс Tkinter? - PullRequest
0 голосов
/ 25 августа 2018

Интересно, как я могу добавить линейную диаграмму matplotlib в tkinter.Вот мой код:

import matplotlib.pyplot as plt
from tkinter import *
import tkinter as tk
from tkinter import ttk
from pylab import *

root = tk.Tk()
root.geometry('500x700')

firstentry = StringVar()
secondentry = StringVar()


class Random():
    def _init_(self):
        self.label1 = None
        self.label2 = None
        self.userEntry = None
    def firstentry(self):
        self.label1 = ttk.Label(text="Enter:")
        self.label1.pack()
        self.userEntry = ttk.Entry(textvariable=firstentry)
        self.userEntry.pack()
        self.button_2 = Button(root, text="Enter", command=self.secondentry)
        self.button_2.pack()
    def secondentry(self):
        self.label2 = ttk.Label(text="Enter:")
        self.label2.pack()
        self.userEntry = ttk.Entry(textvariable=secondentry)
        self.userEntry.pack()
        self.button_3 = Button(root, text="Enter", command=self.line_chart)
        self.button_3.pack()
    def line_chart(self):
        pass

random = Random()

button_1 = Button(root, text="button", command=lambda:random.firstentry())
button_1.pack()

root.mainloop()

Я хочу, чтобы программа отображала линейный график после того, как пользователь отправил второй вход, чтобы функция line_chart отображала его после отправки входных данных.Тем не менее, я понятия не имею, как это сделать.Может кто-нибудь, пожалуйста, объясните, как я могу это встроить?

1 Ответ

0 голосов
/ 25 августа 2018

В Интернете достаточно документации, если вы не торопитесь с Google перед публикацией.

в любом случае

вот пример

import matplotlib as mpl
import numpy as np
import sys
if sys.version_info[0] < 3:
  import Tkinter as tk
else:
  import tkinter as tk
  import matplotlib.backends.tkagg as tkagg
  from matplotlib.backends.backend_agg import FigureCanvasAgg


def draw_figure(canvas, figure, loc=(0, 0)):
  figure_canvas_agg = FigureCanvasAgg(figure)
  figure_canvas_agg.draw()
  figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
  figure_w, figure_h = int(figure_w), int(figure_h)
  photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)

  # Position: convert from top-left anchor to center anchor
  canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo)

  # Unfortunately, there's no accessor for the pointer to the native renderer
  tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)

  # Return a handle which contains a reference to the photo object
  # which must be kept live or else the picture disappears
  return photo

# Create a canvas
w, h = 300, 200
window = tk.Tk()
window.title("A figure in a canvas")
canvas = tk.Canvas(window, width=w, height=h)
canvas.pack()

# Generate some example data
X = np.linspace(0, 2 * np.pi, 50)
Y = np.sin(X)

# Create the figure we desire to add to an existing canvas
fig = mpl.figure.Figure(figsize=(2, 1))
ax = fig.add_axes([0, 0, 1, 1])
ax.plot(X, Y)

# Keep this handle alive, or else figure will disappear
fig_x, fig_y = 100, 100
fig_photo = draw_figure(canvas, fig, loc=(fig_x, fig_y))
fig_w, fig_h = fig_photo.width(), fig_photo.height()

# Add more elements to the canvas, potentially on top of the figure
canvas.create_line(200, 50, fig_x + fig_w / 2, fig_y + fig_h / 2)
canvas.create_text(200, 50, text="Zero-crossing", anchor="s")

# Let Tk take over
tk.mainloop()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...