gpt4 book ai didi

python - 如何在没有任何控件可见的情况下显示 matplotlib 交互式窗口?

转载 作者:太空宇宙 更新时间:2023-11-04 00:53:12 24 4
gpt4 key购买 nike

我需要在用户 Xfce4 桌面上显示 PNG。到目前为止,我使用的是在交互式 matplotlib 窗口中显示 PNG 的 python 脚本:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread("My.png")
plt.imshow(img)
plt.show()

虽然这很不吸引人。有没有办法删除所有交互式控件,图像周围的所有边框空间(轴?),并在启动时将窗口调整为特定的宽度/高度?

或者,是否有更好的选择来在桌面上提供图像的轻量级和静态显示?当然不一定是 python/matplotlib。

最佳答案

当然可以,但到那时,您可能会考虑改用“裸”GUI 工具包。

无论如何,这是 matplotlib 方式:

import matplotlib.pyplot as plt

# Note that the size is in inches at 80dpi.
# To set a size in pixels, divide by 80.
fig = plt.figure(figsize=(4, 5))

# Now we'll add an Axes that takes up the full figure
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off') # Hide all ticks, labels, outlines, etc.

# Display the image so that it will stretch to fit the size
# of the figure (pixels won't be square)
ax.imshow(plt.imread('test.png'), aspect='auto')

plt.show()

除了隐藏工具栏之外,这会做所有事情。要隐藏工具栏,您需要特定于后端。您有两个选择:1) 手动创建窗口并将 matplotlib Canvas 嵌入其中,2) 使用特定于后端的方法隐藏工具栏。

作为隐藏工具栏的示例,使用基于 qt 的后端,您可以:

import matplotlib
matplotlib.use('qt4agg')
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4, 5))
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')

ax.imshow(plt.imread('test.png'), aspect='auto')

# qt specific!
fig.canvas.toolbar.setVisible(False)

plt.show()

对于 Tk 后端,您可以:

import matplotlib
matplotlib.use('tkagg')
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(4, 5))
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')

ax.imshow(plt.imread('test.png'), aspect='auto')

# Tk specific!
fig.canvas.toolbar.pack_forget()

plt.show()

相比之下,如果您想一起跳过 matplotlib 并只使用 Tkinter,您可以这样做:

import Tkinter as tk
from PIL import ImageTk

root = tk.Tk()

im = ImageTk.PhotoImage(file='test.png')
panel = tk.Label(root, image=im)
panel.pack(fill=tk.BOTH, expand=True)

root.mainloop()

这会在屏幕上以一像素对一像素的形式显示图像,并且不允许调整大小。但是,它是您所能获得的最小值。

关于python - 如何在没有任何控件可见的情况下显示 matplotlib 交互式窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36212204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com