首页 > 解决方案 > 如何在 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

标签: pythonpython-3.xpyqtpyqt5python-imaging-library

解决方案


您的问题令人困惑,因为如果分析了您所指出的内容,则可以将其解释为:

  • 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))
    

推荐阅读