【问题标题】:Matplotlib plot without whitespace in tkinter frametkinter 帧中没有空格的 Matplotlib 绘图
【发布时间】:2021-05-28 16:51:28
【问题描述】:

我试图在 tkinter 框架中显示灰度图像(使用 matplotlib 制作)。显示图像本身,但在实际图像的每一侧和 tkinter 框架边框之间只有一些空白。关于如何避免使用空白绘制图像的任何想法?

我目前使用的代码:

from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
        
fig = Figure(figsize=(20, 20))
ax = fig.add_subplot(111)
ax.imshow(self.data, cmap="Greys", interpolation=None)
ax.axis("off")

canvas = FigureCanvasTkAgg(fig, master=self.frame)
canvas.get_tk_widget().pack()
canvas.draw()

代码在框架中生成以下输出:

这大概是它的样子(当然图像质量更好,但你明白了):

【问题讨论】:

    标签: python python-3.x matplotlib tkinter


    【解决方案1】:

    看起来空格在绘图和 GUI 中都存在,所以问题出在 matplotlib 方面。 fig.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.01) 方法可以减少这个空白。

    【讨论】:

      【解决方案2】:

      fig.add_axes - 为图形添加轴。

      rect : sequence of float
         The dimensions [left, bottom, width, height] of the new Axes. All quantities are in fractions of figure width and height.
      

      示例代码,

      from matplotlib.figure import Figure
      from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
      import tkinter as tk
      
      root = tk.Tk()
      frame = tk.Frame(root)
      frame.pack()
      fig = Figure(figsize=(5, 5))
      """
      fig.add_axes - Add an Axes to the figure.
          rect : sequence of float
              The dimensions [left, bottom, width, height] of the new Axes. All
              quantities are in fractions of figure width and height.
      """
      ax = fig.add_axes([0, 0, 1, 1])
      ax.plot(range(10))
      ax.set_xlim([0, 9])
      ax.set_ylim([0, 9])
      
      canvas = FigureCanvasTkAgg(fig, master=frame)
      canvas.get_tk_widget().pack()
      canvas.draw()
      
      root.mainloop()
      

      【讨论】:

        猜你喜欢
        • 2022-08-13
        • 2017-07-19
        • 2011-01-09
        • 2021-10-07
        • 1970-01-01
        • 2021-04-09
        • 2020-07-02
        • 1970-01-01
        • 2012-04-17
        相关资源
        最近更新 更多