为什么文本框在MATPLOTLIB中这么慢?

时间:2018-09-25 18:06:45

标签: user-interface matplotlib textbox

我已经在matplotlib中准备了一个GUI,它具有多个图形和一个文本框 文本框从用户那里收到一个值,图形将被更新。 问题在于,文本框太笨拙,用户单击时需要花费大量时间进行更新。

这是我正在使用的命令

text_box = TextBox(axbox,'Day:',hovercolor ='0.975',label_pad = 0.1,initial = initial_text)

1 个答案:

答案 0 :(得分:0)

TextBox速度很慢,因为每次按键时都会重新绘制整个matplotlib图形(因此,添加更多子图和其他可绘制对象时,它会变慢)。如ImportanceOfBeingErnest所示,您可以使用后端获取快速文本框(请参见下面的演示代码)。

Tk已预装在MacOS和Linux上。您可能需要根据开发环境在Windows上安装它(请参见https://tkdocs.com/tutorial/install.html

import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.widgets import TextBox

class TextBoxDemo(object):
    def __init__(self):
        self.root = tk.Tk()
        self.root.wm_title("Speed Comparison: TextBox vs Tk Entry")
        self.create_ui(self.root)
        self.root.mainloop()

    def create_ui(self, parent):
        # create some matplotlib subplots (drawables)
        rows = 4
        cols = 4
        grid = gridspec.GridSpec(rows, cols, left=.1, right=1-0.05,
                                 top=1-.05, bottom=.15, wspace=.5, hspace=.5)
        figure = plt.figure(figsize=(5, 5), dpi=100)
        for k in range(rows*cols):
            figure.add_subplot(grid[k]).plot([0, 1, 2, 0, 1, 2])

        # create a matplotlib TextBox
        tb_axis = plt.axes([0.17, 0.02, 0.81, 0.05])
        self.textbox = TextBox(tb_axis, 'TextBox:', label_pad=.04)

        # draw the matplotlib drawables on the tk canvas
        canvas = FigureCanvasTkAgg(figure, parent)
        self.canvas_widget = canvas.get_tk_widget()
        self.canvas_widget.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        # connect event handlers
        canvas.mpl_connect("key_press_event", self.on_keypress)
        canvas.mpl_connect("button_press_event", self.on_click)

        # now, create a labeled tk entry box (for comparison)
        label = tk.Label(parent, text='Tk Entry:', width=8)
        label.pack(side=tk.LEFT, padx=0, pady=5)
        entry = tk.Entry(parent)
        entry.pack(fill=tk.X, padx=5, pady=5)

    def on_click(self, event):
        if event.inaxes == self.textbox.ax:
            self.canvas_widget.focus_set()
            self.textbox._click(event)

    def on_keypress(self, event):
        if event.inaxes == self.textbox.ax:
            self.textbox._keypress(event)

if __name__ == "__main__":
    TextBoxDemo()