我正在使用tkinter将一些matplotlib图集成到GUI中。它可以成功绘制图形,但是会在第0行和第1行之间创建多余的空间,并用一堆像素填充它。我似乎无法弄清楚哪里出了问题...我相信这里是相关的代码。我还附上了该问题的屏幕截图。
from tkinter import *
from tkinter import ttk
import numpy as np
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
def budget_plot(BF, tags, mark):
'''
Plots the total amount spent per month of the tags passed to this function
'''
x_axis_labels = BF.months()
y_axis = list()
for tag in tags:
temp = list()
for month in x_axis_labels:
temp.append(tag_sum(BF, tag)[month])
y_axis.append(temp)
# indices of the x_ticks, to be used for labeling
og_ind = np.arange(len(x_axis_labels))
fig = Figure()
a = fig.add_subplot(111)
for i in range(len(y_axis)):
if mark == 'dot':
a.plot(og_ind, y_axis[i], 'o', markersize = 12, label=tags[i])
else:
a.plot(og_ind, y_axis[i], markersize = 13, label=tags[i])
a.set_xlabel("Month")
a.set_xticks(og_ind)
a.set_xticklabels(x_axis_labels)
a.set_ylabel("Cost [$]")
a.set_title("Total Cost / Month")
a.legend()
return fig
class FinanceApp(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
container = ttk.Frame(self)
container.grid(row=0, column=0)
container.rowconfigure(0, weight=1)
container.columnconfigure(0, weight=1)
# contains all of the pages that can be called.
# keys -> class of a page
# values -> the frames of that page with all of its widgets and attributes
self.frames = dict()
for F in (StartPage, TagsPageOne, TagsPageTwo, TagsPageThree, DifPageOne):
# container is the "mother" frame, self is the controller (i.e. the root (Tk) in this case)
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="NSEW")
self.show_frame(StartPage)
def show_frame(self, cont):
# cont -> class of a page
# call the frame that is associated with the page (class) then raise it to the foreground
frame = self.frames[cont]
frame.tkraise()
class TagsPageThree(ttk.Frame):
def __init__(self, parent, controller):
ttk.Frame.__init__(self, parent)
button_home = ttk.Button(self, text = "Start Page", command = lambda: controller.show_frame(StartPage))
button_home.grid(row=0, column=0, sticky="NSEW")
button_home.rowconfigure(0, weight=1)
button_home.columnconfigure(0, weight=1)
fig = budget_plot(file, ['Grocery'], 'line')
canvas = FigureCanvasTkAgg(fig, self)
canvas.draw()
canvas.get_tk_widget().grid(row=1, column=0)
canvas._tkcanvas.grid(row=1, column=0)