如何在连接到 Raspberry Pi 的显示器上显示 GUI?

Posted

技术标签:

【中文标题】如何在连接到 Raspberry Pi 的显示器上显示 GUI?【英文标题】:How to display a GUI on a display connected to a Raspberry Pi? 【发布时间】:2020-11-16 23:00:16 【问题描述】:

编辑:用“export DISPLAY=:0”解决

原来的问题:

我有一个Display 连接到我的 Raspberry Pi 3B+。它工作正常,我可以看到 Raspberry 的桌面。

我在我的 PC 上通过我的 Raspberry 上的 SSH 在 VSCode 上工作。因此,当我启动 python 脚本时,它在 Raspberry 上运行,但终端输出在我的 PC 上的 VSCode 中。到目前为止一切顺利。

我现在用 PyQt5 编写了一个简单的 GUI,并希望在 Raspberry 的显示屏上显示它。但我总是得到错误:

qt.qpa.screen: QXcbConnection: Could not connect to display. Could not connect to any X display.

所有的解决方案都是如何解决隧道问题,Raspberry 可以在我的 PC 显示器上显示 GUI,但我希望它只显示在 Raspberry 的显示器上,否则工作正常。

有什么建议吗?

这是我的代码,通过 ssh 在 raspberry 上执行:

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys


class MyWindow(QMainWindow):
    def __init__(self):
        super(MyWindow,self).__init__()
        self.initUI()

    def button_clicked(self):
        self.label.setText("you pressed the button")
        self.update()

    def initUI(self):
        self.setGeometry(0, 0, 100, 100)
        self.setWindowTitle("Tech With Tim")

        self.label = QtWidgets.QLabel(self)
        self.label.setText("my first label!")
        self.label.move(50,50)

        self.b1 = QtWidgets.QPushButton(self)
        self.b1.setText("click me!")
        self.b1.clicked.connect(self.button_clicked)

    def update(self):
        self.label.adjustSize()


def window():
    app = QApplication(sys.argv)
    win = MyWindow()
    win.show()
    sys.exit(app.exec_())

window()

【问题讨论】:

从远程 SSH 运行时,您必须设置 DISPLAY 环境,通常是 :0.0(从 X 启动时通常在虚拟终端上自动设置)。在运行脚本之前尝试使用export DISPLAY=:0.0 就是这样!非常感谢! 请不要编辑添加“已解决”备注的问题。正如tour(您应该关注的)指出的那样:“[*** i] 不是讨论论坛。”。您可以添加自己的答案,或者等待其他人给出答案,感谢这种情况下的 cmets,有人发现了它。 请注意,在这种情况下,这实际上是另一个问题的重复问题:Cannot connect to X server :0.0 with a Qt application(这也意味着它可能会被关闭)。 【参考方案1】:

在运行脚本之前设置 DISPLAYXAUTHORITY 变量环境。 例如在systemctl 服务文件中:

[Unit]
Description=Start Clock

[Service]
Environment=DISPLAY=:0
Environment=XAUTHORITY=/home/pi/.Xauthority
ExecStart=/usr/bin/python3 /home/pi/clock.py
Restart=always
RestartSec=10s
KillMode=process
TimeoutSec=infinity

[Install]
WantedBy=graphical.target

【讨论】:

以上是关于如何在连接到 Raspberry Pi 的显示器上显示 GUI?的主要内容,如果未能解决你的问题,请参考以下文章

如何将 Raspberry Pi 3 连接到 Visual Studio? (更新)

如何使用 Wifi Direct 将我的 Windows 10 PC 连接到我的 Raspberry Pi 3?

在(Raspberry Pi)树莓派上安装NodeJS

如何使用Raspberry Pi将一个屏幕分成两个?

将Raspberry PI 3与Android Things连接到Arduino [已关闭]

如何使用 QT 在 Raspberry Pi 上的 LCD 和 HDMI 上同时在 Linux 中绘制图像?