0

The code is based on: https://github.com/PySimpleGUI/PySimpleGUI/blob/master/DemoPrograms/Demo_Matplotlib_Embedded_Toolbar.py One custom button is added to the toolbar and if we call, ex. sg.popup from callback function for this button main loop become broken - no events are returned from any button (Plot and Exit in the example).

import PySimpleGUI as sg
import numpy as np
import os
import sys
import matplotlib.backends
import base64

"""
    Embedding the Matplotlib toolbar into your application
    Based on:
    https://github.com/PySimpleGUI/PySimpleGUI/blob/master/DemoPrograms/Demo_Matplotlib_Embedded_Toolbar.py

"""

# ------------------------------- This is to include a matplotlib figure in a Tkinter canvas
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

if os.path.isfile("axsminmax.png") == False:
    toolbarpng1 = b'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAABsklEQVRYhe3Xz2oUQRAG8F8mvoH4CuJbeDagQvBoLtldl+BJIko04j98BiX+IycPXox61zyFkKsevedkxkPXkHHipHd2nQ2KHxTM1lbX9011d/U0s2GE4Yw5psYtlGF3502+GcQ/wsoQNBfcDsLX2MVnPAvfRt/k4yDaRoFPYUX4Sqx0SXiqo4CveIyHOKj5D7CKb/jeMedMqCowNYo/JOTvFdB1DTTxRlp4/xZWcKGHvMtYywXdlEr6JBNX4BreY0c6E3Lr6X7kftAWUPX2bSxmyD9G7F5YiQ8ZEQvYahNRb6+5NxlFbL2ca+EbZMYWeFEXsRAJt6RDZdevHa7C24ghlf0czjZi9vAFl+P3GFdaRJyXqnx90j4w6VYrW57bsF89bMSAl/JTMNQ+BauZsYU0zSXWm39OKqKQFlxzEe5IU9qGRYcn5hHypohHxyQSREO8CxtkyElb+1jyCgNczAVNgSVc7SHvyWIsdcQTw/8PkrkLWJK20+8Oq0Lavpf6FHAad/CqMbbAc9zDmY45O+OGoxeTp+Hb7Ju8QvXtUL+a9X4ramLd4eV0bm/exChsavwEAXVwI8ngt8MAAAAASUVORK5CYII='
    with open("axsminmax.png", "wb") as fh:
        fh.write(base64.decodebytes(toolbarpng1))

def draw_figure_w_toolbar(canvas, fig, canvas_toolbar):
    if canvas.children:
        for child in canvas.winfo_children():
            child.destroy()
    if canvas_toolbar.children:
        for child in canvas_toolbar.winfo_children():
            child.destroy()
    figure_canvas_agg = FigureCanvasTkAgg(fig, master=canvas)
    figure_canvas_agg.draw()
    toolbar = Toolbar(figure_canvas_agg, canvas_toolbar)
    toolbar.update()
    figure_canvas_agg.get_tk_widget().pack(side='right', fill='both', expand=1)

def get_res_file_path(fname):
    if hasattr(sys, "_MEIPASS"):
        fpath = os.path.join(sys._MEIPASS, fname)
    else:
        basedir = os.path.abspath(os.getcwd())
        fpath = basedir+'/'+fname
    return fpath

def callback_func_P(NavigationToolbar2TK):
    def wrapper(): 
        print('Plot on min/max from toolbar')
        sg.popup('This window blocks main loop.\nPlot, Exit and Alive? buttons not working after that.\nAnd Terminal window could be closed by x only!')
    return wrapper

class Toolbar(NavigationToolbar2Tk):
    def __init__(self, *args, **kwargs):
        self.toolitems = NavigationToolbar2Tk.toolitems+((None, None, None, None),)
        super(Toolbar, self).__init__(*args, **kwargs)
        self._buttons["Plotmm"] = button = self._Button("Plotmm", get_res_file_path('axsminmax.png'), toggle=False, command=callback_func_P(self))
        Tooltip = getattr(matplotlib.backends, '_backend_tk').ToolTip
        Tooltip.createToolTip(button, "Plot data on min/max")

# ------------------------------- PySimpleGUI CODE

layout = [
    [sg.T('Graph: y=sin(x)')],
    [sg.B('Plot'), sg.B('Exit')],
    [sg.T('Controls:')],
    [sg.Canvas(key='controls_cv')],
    [sg.T('Figure:')],
    [sg.Column(
        layout=[
            [sg.Canvas(key='fig_cv',
                       # it's important that you set this size
                       size=(400 * 2, 400)
                       )]
        ],
        background_color='#DAE0E6',
        pad=(0, 0)
    )],
    [sg.B('Alive?')]

]

window = sg.Window('Graph with controls', layout)

while True:
    event, values = window.read()
    print(event, values)
    if event in (sg.WIN_CLOSED, 'Exit'):  # always,  always give a way out!
        break
    elif event is 'Plot':
        # ------------------------------- PASTE YOUR MATPLOTLIB CODE HERE
        plt.figure(1)
        fig = plt.gcf()
        DPI = fig.get_dpi()
        # ------------------------------- you have to play with this size to reduce the movement error when the mouse hovers over the figure, it's close to canvas size
        fig.set_size_inches(404 * 2 / float(DPI), 404 / float(DPI))
        # -------------------------------
        x = np.linspace(0, 2 * np.pi)
        y = np.sin(x)
        plt.plot(x, y)
        plt.title('y=sin(x)')
        plt.xlabel('X')
        plt.ylabel('Y')
        plt.grid()

        # ------------------------------- Instead of plt.show()
        draw_figure_w_toolbar(window['fig_cv'].TKCanvas, fig, window['controls_cv'].TKCanvas)

window.close()

If instead of sg.popup we'll create our own window the result will be same.

Steps to reproduce. 1.Start script. 2.Press button Plot. 3.Press most right toolbar' button (tooltip-'Plot data on min/max'). 4.Press Plot or Exit buttons - nothing is happen.

1 Answer 1

0

Know nothing about the relation between function wrapper and tkinter.

My suggestion is to use method window.write_event_value to generate an event to main loop to do something about the GUI.

def callback_func_P(NavigationToolbar2TK):
    def wrapper():
        print('Plot on min/max from toolbar')
        window.write_event_value('Popup', 'This window blocks main loop.\nPlot, Exit and Alive? buttons not working after that.\nAnd Terminal window could be closed by x only!')
    return wrapper

and this in the main event loop

    elif event == 'Popup':
        sg.popup(values[event])
3
  • This can be accepted as workaround for this particular case. But what the real cause of such behavior? For example, it is not comfortable to send all error messages from functions which are called by toolbar buttons to the main event loop.
    – Alex
    Feb 5 at 14:15
  • Not an expert of matplotlib, so I cannot tell you what the root cause is. Using method window.write_event_value to generate an event to event loop is a good way to isolate the thread issue or something like it.
    – Jason Yang
    Feb 5 at 15:09
  • After some thought, I decided that redirecting all events from the new toolbar buttons to the main event loop is a good idea. You don't have to do anything in the callback functions, just inform the main loop about the button being pressed in the toolbar. This makes the code more readable. So I accept this answer as solving my problem. Thank you.
    – Alex
    Feb 6 at 11:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.