matplotlib 在Windows上使用TkAgg后端将窗口设置为全屏后,图伸出窗口

polkgigr  于 2023-10-24  发布在  Windows
关注(0)|答案(1)|浏览(191)

我正在尝试编写一个Python函数,它使用pyplot在全屏模式下显示图像网格。当窗口打开时(Windows 10上的TkAgg交互式后端),我的部分图在屏幕外,如下图所示:

它应该是这样的:

如何使图形正确显示在屏幕上?
下面是我的代码:

  1. from PIL import Image
  2. import matplotlib.pyplot as plt
  3. def imageGrid(data_obj, grid=(3,3), start_idx=0):
  4. # set figure size to 1 inch by 1 inch
  5. figure = plt.figure(figsize=(1,1))
  6. cols, rows = grid
  7. idx = start_idx
  8. for i in range(1, cols * rows + 1):
  9. img = data_obj[idx]
  10. figure.add_subplot(rows, cols, i)
  11. plt.axis("off")
  12. plt.imshow(img, cmap="gray")
  13. idx += 1
  14. plt.subplots_adjust(wspace=0, hspace=0, left=0, right=1, bottom=0, top=1)
  15. # make the window open in full screen (this line is breaking it)
  16. plt.get_current_fig_manager().window.state('zoomed')
  17. plt.show()
  18. list_of_images = [Image.open("Screenshot 2023-08-30 170601.png") for i in range(9)]
  19. imageGrid(list_of_images)

为了使窗口全屏显示,我按照herehere的说明操作。
我曾经试过把数字设置为1乘1英寸,让数字变小,这肯定比我的屏幕小,但无论我怎么设置,似乎都没有效果。
如果我手动调整窗口大小(在全屏模式下进出),问题就解决了,所以我能够捕捉到想要的外观。

gjmwrych

gjmwrych1#

这似乎是一个bug in matplotlib,但我已经找到了一种方法来正确显示它的第一次窗口打开。然而,请注意,一旦窗口是手动调整大小,这将“overcorrect”和结果将不会是相同的。以下是步骤:

  • 运行代码,使其显示不正确的图
  • 单击屏幕右下角的滑块图标
  • 设置参数“right”和“bottom”,使图形显示在屏幕上
  • 使用上面获得的值调用plt.subplots_adjust

最后,我将plt.subplots_adjust(wspace=0, hspace=0, left=0, right=1, bottom=0, top=1)改为plt.subplots_adjust(wspace=0, hspace=0, left=0, right=0.565, bottom=0.442, top=1),因此最终代码为:

  1. from PIL import Image
  2. import matplotlib.pyplot as plt
  3. def imageGrid(data_obj, grid=(3,3), start_idx=0):
  4. # set figure size to 1 inch by 1 inch
  5. figure = plt.figure(figsize=(1,1))
  6. cols, rows = grid
  7. idx = start_idx
  8. for i in range(1, cols * rows + 1):
  9. img = data_obj[idx]
  10. figure.add_subplot(rows, cols, i)
  11. plt.axis("off")
  12. plt.imshow(img, cmap="gray")
  13. idx += 1
  14. plt.subplots_adjust(wspace=0, hspace=0, left=0, right=0.565, bottom=0.442, top=1)
  15. # make the window open in full screen (this line is breaking it)
  16. plt.get_current_fig_manager().window.state('zoomed')
  17. plt.show()
  18. list_of_images = [Image.open("Screenshot 2023-08-30 170601.png") for i in range(9)]
  19. imageGrid(list_of_images)
展开查看全部

相关问题