python - 如何在 PyQt 画布中插入 PIL.Image - PyQt5
问题描述
我想在我的应用程序的仪表中显示一些数据。我正在使用pyqt5。
我正在创建一个canvas
显示我的情节或仪表的地方(有时是情节,有时是仪表):
class MplCanvas(FigureCanvasQTAgg):
def __init__(self, parent=None, width=8, height=6, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
super(MplCanvas, self).__init__(fig)
并将其添加canvas
到我的主布局中:
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.canvas = MplCanvas(self, width=12, height=8, dpi=100)
self.layout_plot.addWidget(self.canvas)
self.show()
我找到了有关如何创建仪表的链接:
import PIL
from PIL import Image
percent = 20 # Percent for gauge
output_file_name = 'new_gauge.png'
percent = percent / 100
rotation = 180 * percent # 180 degrees because the gauge is half a circle
rotation = 90 - rotation # Factor in the needle graphic pointing to 50 (90 degrees)
dial = Image.open('needle.png')
dial = dial.rotate(rotation, resample=PIL.Image.BICUBIC, center=loc) # Rotate needle
gauge = Image.open('gauge.png')
gauge.paste(dial, mask=dial) # Paste needle onto gauge
gauge.save(output_file_name)
我尝试以gauge
这种方式将其添加到我的画布中:
dial = Image.open('needle.png')
dial = dial.rotate(rotation, resample=PIL.Image.BICUBIC, center=loc) # Rotate needle
gauge = Image.open('gauge.png')
gauge.paste(dial, mask=dial) # Paste needle onto gauge
self.layout_plot.removeWidget(self.canvas)
self.layout_plot.addWidget(gauge)
self.canvas.draw()
我收到此错误:
TypeError: addWidget(self, QWidget, stretch: int = 0, alignment: Union[Qt.Alignment, Qt.AlignmentFlag] = Qt.Alignment()): argument 1 has unexpected type 'PngImageFile'
如何gauge
在我的中添加这个canvas
?
解决方案
您的问题令人困惑,因为如果分析了您所指出的内容,则可以将其解释为:
How to add the PIL.image in a layout to which the canvas was also added. If so, then the problem is that the addWidget method expects a QWidget so you have to use a QWidget like QLabel to put the image there, and then put the QLabel in the layout:
from PIL.ImageQt import ImageQt
im = ImageQt(gauge).copy() pixmap = QtGui.QPixmap.fromImage(im) label = QtWidgets.QLabel() label.setPixmap(pixmap) self.layout_plot.addWidget(label)
How to add the PIL.Image inside the canvas, and in that case you should not use the layout but the imshow method:
self.canvas.axes.imshow(np.asarray(gauge))
推荐阅读
- c# - 如何过滤包含数字的参数?C# .NET
- excel - 将数据透视表用于加班数据和其他趋势分析列
- python - 如何在python中按升序对pd.cut(bins)进行排序
- azure-ad-b2c - Azure B2C 注册或登录策略 - 用户创建或刚刚注册
- javascript - Node.js AES 解密 Base64 字符串
- javascript - 如何在 vue typescript 中处理异步/等待中的错误
- php - 通过 mailgun 的出站电子邮件被发送两次
- sql - 从 postgres 数据库中删除重复条目
- java - 如何使用 thrift 生成器作为 maven 依赖项(如何避免引用 .exe 文件)?
- javascript - ChartJS:datalabels:在饼图中显示百分比值