简体   繁体   English

Python:在tkinter中正确嵌入带有滑块的matplotlib图

[英]Python: Embed a matplotlib plot with slider in tkinter properly

I have created this plot in pyplot which has a slider to view a certain range of the data. 我在pyplot中创建了该图,该图具有一个滑块,可以查看一定范围的数据。

import random
import matplotlib
import tkinter as Tk
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)

y_values = [random.randrange(20, 40, 1) for _ in range(40)]
x_values = [i for i in range(40)]

l, = plt.plot(x_values, y_values)
plt.axis([0, 9, 20, 40])

ax_time = plt.axes([0.12, 0.1, 0.78, 0.03])
s_time = Slider(ax_time, 'Time', 0, 30, valinit=0)


def update(val):
    pos = s_time.val
    ax.axis([pos, pos+10, 20, 40])
    fig.canvas.draw_idle()
s_time.on_changed(update)

#plt.show()

matplotlib.use('TkAgg')

root = Tk.Tk()
root.wm_title("Embedding in TK")

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

Tk.mainloop()

The problem is, it seems unresponsive when embedded in a tkinter window, although when I show it with plt.show() (meaning the code after this, is commented) works correctly. 问题是,尽管当我使用plt.show()(表示此后的代码已注释)显示时,嵌入到tkinter窗口中时似乎没有响应。 What is the right way to do this? 什么是正确的方法?

I figured this one out. 我想通了。 The figure needs to be added to the canvas before creating the plot. 在创建图之前,需要将图形添加到画布。

import random
import matplotlib
import tkinter as Tk
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

matplotlib.use('TkAgg')

root = Tk.Tk()
root.wm_title("Embedding in TK")
fig = plt.Figure()
canvas = FigureCanvasTkAgg(fig, root)
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

ax=fig.add_subplot(111)
fig.subplots_adjust(bottom=0.25)

y_values = [random.randrange(20, 40, 1) for _ in range(40)]
x_values = [i for i in range(40)]

ax.axis([0, 9, 20, 40])
ax.plot(x_values, y_values)

ax_time = fig.add_axes([0.12, 0.1, 0.78, 0.03])
s_time = Slider(ax_time, 'Time', 0, 30, valinit=0)


def update(val):
    pos = s_time.val
    ax.axis([pos, pos+10, 20, 40])
    fig.canvas.draw_idle()
s_time.on_changed(update)

Tk.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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