我试图在与图像相同的窗口或画布中显示BMP图像的MatPlotLib图。代码已经可以显示图像了,我已经有了数据图,我只是在将图形嵌入到GUI中时遇到了麻烦。我尝试引用http://matplotlib.org/examples/user_interfaces/embedding_in_tk2.html,但我有点难过,试图将其加入到此代码中。
理想情况下,我会在图像下方显示情节。
这是我的代码:
import tkinter as tk
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
from scipy import misc
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.pos = []
self.master.title("BMP Image GUI")
self.pack(fill=BOTH, expand=1)
self.counter = 0
menu = Menu(self.master)
self.master.config(menu=menu)
# File Bar
file = Menu(menu)
file.add_command(label="Open Image 1", command=self.openImage1)
file.add_command(label="Exit", command=self.client_exit)
menu.add_cascade(label="File", menu=file)
self.canvas = tk.Canvas(self)
self.canvas.pack(fill=tk.BOTH, expand=True)
self.image = None
self.image2 = None
def client_exit(self):
exit()
def openImage1(self):
filename = filedialog.askopenfilename(initialdir=os.getcwd(), title="Select BMP File",
filetypes=[("BMP Files", "*.bmp")])
if not filename:
return
# Image 1 Data Graph
image = misc.imread(filename, flatten=False, mode="RGB")
sumArray1 = []
for i in range(0, image.shape[0]-1):
sumArray1.append(np.sum(image[i]))
np.asarray(sumArray1)
fig = plt.figure(figsize=(10,3.75), dpi=96)
plt.plot(sumArray1)
# Image 1
load = Image.open(filename)
load1 = load.resize((960, 720), Image.ANTIALIAS)
w, h = load1.size
width, height = root.winfo_screenmmwidth(), root.winfo_screenheight()
if self.image is None:
self.render = ImageTk.PhotoImage(load1)
self.image = self.canvas.create_image((w / 2, h / 2), image=self.render)
root.geometry("%dx%d" % (w, height))
root = tk.Tk()
root.geometry("%dx%d" % (300, 300))
root.title("BMP Image GUI")
app = Window(root)
app.pack(fill=tk.BOTH, expand=1)
root.mainloop()
答案 0 :(得分:0)
我不知道这是否有效,但是创建了第二个画布canvas2
,它似乎做了那个工作。在此之前,我正在使用与BMP图像相同的画布,并且它没有显示出来。也许只有一种画布才能做到这一点。
if self.image is None:
self.render = ImageTk.PhotoImage(load1)
self.image = self.canvas.create_image((w / 2, h / 2), image=self.render)
root.geometry("%dx%d" % (w, height))
self.canvas2 = FigureCanvasTkAgg(fig, master=root)
self.canvas2.show()
self.canvas2.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=0)
self.canvas2._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=0)