我有一个交互式绘图的代码,该代码允许通过鼠标滚动切片滚动查看3D图像。它还包括一个滑动条,用于调整对比度。
我一直试图将其嵌入到Tkinter GUI中,例如,在以下示例代码的帮助下:https://matplotlib.org/examples/user_interfaces/embedding_in_tk.html
但是我不太了解我的代码应该放在哪里。
这是我当前拥有的应用程序:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Slider
class IndexTracker(object):
def __init__(self, ax, X):
self.ax = ax
ax.set_title('use scroll wheel to navigate images')
self.X = X
rows, cols, self.slices = X.shape
self.ind = self.slices//2
self.im = ax.imshow(self.X[:, :, self.ind], cmap='gray')
self.update()
def onscroll(self, event):
print("%s %s" % (event.button, event.step))
if event.button == 'up':
self.ind = (self.ind + 1) % self.slices
else:
self.ind = (self.ind - 1) % self.slices
self.update()
def contrast(self, event):
print('Changing contrast')
print(smax.val)
self.im.set_clim([0,smax.val])
self.update()
def update(self):
self.im.set_data(self.X[:, :, self.ind])
self.ax.set_ylabel('slice %s' % self.ind)
self.im.axes.figure.canvas.draw()
##### Create some random volumetric data
im = np.array(np.random.rand(10,10,10))
##### Initialize Tracker object with the data and Slider
fig, ax = plt.subplots(1,1)
axmax = fig.add_axes([0.25, 0.01, 0.65, 0.03])
smax = Slider(axmax, 'Max', 0, np.max(im), valinit=50)
tracker = IndexTracker(ax, im)
fig.canvas.mpl_connect('scroll_event', tracker.onscroll)
smax.on_changed(tracker.contrast)
plt.show()
我不知道我需要嵌入到Tkinter应用程序中的确切含义是fig
还是IndexTracker
?如何替换fig.canvas.mpl_connect('scroll_event', tracker.onscroll)
,使其在TKinter GUI中起作用?
答案 0 :(得分:1)
将其嵌入到tkinter
中没有什么特别的-您首先创建一个FigureCanvasTkAgg
对象,然后进行其余操作。您唯一需要更改的是代替plt
,而需要使用引述的示例中显示的Figure
。
import numpy as np
from matplotlib.widgets import Slider
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
class IndexTracker(object):
...
import tkinter as tk
root = tk.Tk()
fig = Figure()
canvas = FigureCanvasTkAgg(fig, root)
canvas.get_tk_widget().pack(fill="both", expand=True)
im = np.array(np.random.rand(10,10,10))
ax = fig.subplots(1,1)
axmax = fig.add_axes([0.25, 0.01, 0.65, 0.03])
smax = Slider(axmax, 'Max', 0, np.max(im), valinit=50)
tracker = IndexTracker(ax, im)
canvas.mpl_connect('scroll_event', tracker.onscroll)
canvas.mpl_connect('button_release_event', tracker.contrast) #add this for contrast change
root.mainloop()