You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

树莓派Raspbian Lite运行PySimpleGUI遇_tkinter.TclError:无DISPLAY变量

解决Raspbian Lite下PySimpleGUI无DISPLAY环境变量错误及触摸LCD适配问题

1. 修复DISPLAY环境变量缺失问题

错误源于Tkinter(PySimpleGUI默认后端)无法找到显示设备,即使未连接物理屏幕,也需指定帧缓冲对应的显示端口:

  • 临时生效:
    export DISPLAY=:0
    
  • 永久生效(重启后仍有效):
    编辑~/.bashrc文件,添加上述命令,然后执行:
    source ~/.bashrc
    

2. 安装最小化X11依赖(无需完整桌面)

Raspbian Lite缺少Tkinter运行必需的X11基础组件,安装最小化包:

sudo apt update && sudo apt install -y xserver-xorg-core xserver-xorg-input-evdev x11-xserver-utils python3-tk

3. 配置帧缓冲与触摸LCD

编辑/boot/config.txt,添加或修改以下配置(根据你的LCD型号调整分辨率、触摸参数):

# 帧缓冲分辨率
framebuffer_width=800
framebuffer_height=480
# 强制HDMI热插拔(无屏幕时仍启用显示)
hdmi_force_hotplug=1
hdmi_group=2
hdmi_mode=87
hdmi_cvt=800 480 60 6 0 0 0
# 触摸LCD驱动示例(以ADS7846为例,替换为你屏幕对应的overlay)
dtoverlay=ads7846,cs=1,penirq=25,penirq_pull=2,speed=50000,keep_vref_on=0,swapxy=0,pmax=255,xohms=150,xmin=200,xmax=3900,ymin=200,ymax=3900

修改后重启树莓派:

sudo reboot

4. 调整PySimpleGUI代码实现全屏、无关闭按钮

修改代码以适配触摸、全屏且隐藏关闭按钮:

import PySimpleGUI as sg

sg.theme('Black')  # 适配LCD的深色主题

# 界面布局示例
layout = [
    [sg.Text("触摸测试", font=('Arial', 22), justification='center', expand_x=True)],
    [sg.Button("点击", size=(12,3), font=('Arial', 18), expand_x=True)]
]

window = sg.Window(
    '触摸应用',
    layout,
    no_titlebar=True,  # 隐藏标题栏(无关闭按钮)
    fullscreen=True,   # 全屏显示
    touch_events=True, # 启用触摸支持
    element_padding=(0,0),
    margins=(0,0)
)

while True:
    event, values = window.read()
    if event == '点击':  # 仅保留业务逻辑触发退出,无关闭按钮
        break

window.close()

5. 启动X服务器并运行程序

Raspbian Lite无桌面环境,需手动启动X服务器后运行程序:

# 启动无光标X服务器到帧缓冲
startx -- -nocursor &
# 运行你的Python程序
python3 /home/pi/your_program.py

如需开机自动运行,编辑/etc/rc.local,在exit 0前添加:

su pi -c "startx -- -nocursor &"
su pi -c "python3 /home/pi/your_program.py &"

触摸校准(可选)

若触摸存在偏移,执行校准命令:

xinput_calibrator

将生成的校准配置写入/etc/X11/xorg.conf.d/99-calibration.conf,重启后生效。

内容的提问来源于stack exchange,提问作者Ray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 18:35:24