简体   繁体   中英

Push Buttons in Tkinter and Matplotlib

I would like to generate a Matplotlib plot in Tkinter via a button push. The button is supposed to start a data collection routine (ultimately from the serial port) and data are to be plotted when the collection process is finished. The code below is simplified and just contains some dummy data. My problem is that no graph appears when pushing the "plot" button.

import tkinter
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg)
from matplotlib.figure import Figure

window = tkinter.Tk()

fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot(1, 1, 1)
canvas = FigureCanvasTkAgg(fig, master=window) 
canvas.draw()

def plotData(ax):
    xs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    ys = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    ax.clear()
    ax.plot(xs, ys)
   
CloseButton = tkinter.Button(master=window, text="Close", command=window.destroy)
PlotButton = tkinter.Button(master=window, text = "Plot", command = lambda: plotData(ax))
    
CloseButton.pack(side=tkinter.LEFT, padx = 10, pady = 10)
PlotButton.pack(side=tkinter.LEFT, padx = 10, pady = 10)

canvas.get_tk_widget().pack(side=tkinter.RIGHT, fill=tkinter.BOTH, expand=1)

tkinter.mainloop()

You need to add canvas.draw() to the end of the function.

def plotData(ax):
    xs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    ys = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    ax.clear()
    ax.plot(xs, ys)
    canvas.draw()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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