如何在 MacBook Pro 的 docker 容器中 运行 tkinter?

How to run tkinter inside a docker container on MacBook Pro?

我正在尝试 运行 python GUI 应用程序,它在我的 MacBook Pro 上的 docker 容器内使用 tkinter 模块。

所以我在 docker 容器中安装了 XQuartz and followed this tutorial 到 运行 一个简单的 tkinter 程序。

这是我收到的错误消息

Traceback (most recent call last):
  File "/app/tkinter_app.py", line 4, in <module>
    root_window = tk.Tk()
  File "/usr/local/lib/python3.8/tkinter/__init__.py", line 2270, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: couldn't connect to display "/private/tmp/com.apple.launchd.knFz0UzqxP/org.xquartz:0"

我的 DISPLAY 环境变量的值为 /private/tmp/com.apple.launchd.knFz0UzqxP/org.xquartz:0

有人知道如何解决这个错误吗?

这是教程中的 Dockerfile

# Slim version of Python
FROM python:3.8.12-slim

# Download Package Information
RUN apt-get update -y

# Install Tkinter
RUN apt-get install tk -y

# Commands to run Tkinter application
CMD ["/app/tkinter_app.py"]
ENTRYPOINT ["python3"]

/app/tkinter_app.py 的第 4 行是 root_window = tk.Tk()

我的 MacOS 版本是 11.6.1

我制作了一个带有 xeyes 的小 docker 图像,用于在我的 Mac 上使用 XQuartz X11 服务器测试 X11 客户端,并将其用作我的 Dockerfile:

# Base Image
FROM alpine:latest

RUN apk update && \
    apk add --no-cache xeyes

# Set a working directory
WORKDIR /work

# Start a shell by default
CMD ["ash"]

然后我这样构建它:

docker build -t setchell/xeyes .

而我 运行 它是这样的:

# Prerequisites
#   brew cask install xquartz
    
# Set your Mac IP address
IP=$(/usr/sbin/ipconfig getifaddr en0)

# Allow connections from Mac to XQuartz
/opt/X11/bin/xhost + "$IP"

# Run container
docker run -it -e DISPLAY="${IP}:0" -v /tmp/.X11-unix:/tmp/.X11-unix setchell/xeyes

一旦进入容器,我就 运行:

xeyes

结果如下:

可能还有更简单的方法,有些步骤可能是不必要的,如果有人知道更简单的方法,请联系我。我总是乐于学习。