WSL Ubuntu下Tkinter无法连接显示":0"问题求助
I’ve run into this exact issue before when building Tkinter projects in WSL Ubuntu—you set DISPLAY to :0 like you think you should, but still hit that annoying connection error. The core problem here is that WSL doesn’t come with its own X Window server; it needs to rely on an X server running on your Windows host to render the GUI to your laptop screen. Here’s how I fixed it:
Install an X server on Windows
Grab VcXsrv (it’s free and open-source) from the Microsoft Store—just search for "VcXsrv" and install it. When you launch it, make sure to check "Disable access control" in the "Extra settings" step; this lets WSL connect without permission blocks. Leave all other default settings as-is and start the server.Configure the DISPLAY variable correctly in WSL
WSL can’t use:0directly because that points to a non-existent display inside the WSL environment. Instead, you need to point it to your Windows host’s IP address:- Get your Windows IP from WSL: run
cat /etc/resolv.conf | grep nameserver—the output (something like192.168.x.x) is your Windows machine’s local IP. - Set the DISPLAY variable temporarily:
export DISPLAY=<your_windows_ip>:0.0(replace<your_windows_ip>with the IP you just found). - To make this permanent so you don’t have to set it every time, add the line to your shell config:
- Open
~/.bashrc(or~/.zshrcif you use Zsh) withnano ~/.bashrc - Paste this line at the bottom:
export DISPLAY=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2}'):0.0 - Save and exit (Ctrl+O, Enter, Ctrl+X), then run
source ~/.bashrcto apply the changes.
- Open
- Get your Windows IP from WSL: run
Test if Tkinter works
Run this quick test script to confirm everything’s set up:import tkinter as tk root = tk.Tk() root.title("WSL Tkinter Test") label = tk.Label(root, text="GUI is showing up on your Windows screen!") label.pack(padx=20, pady=20) root.mainloop()If a small window pops up with that message, you’re good to go.
A quick note: The reason export DISPLAY=:0 wasn’t working for you is that WSL doesn’t have a local display device—:0 only makes sense if you’re running an X server inside WSL, which you aren’t. You need to point it to the Windows-side X server instead, which is what the steps above do. Also, make sure VcXsrv is running whenever you want to use Tkinter in WSL.
内容的提问来源于stack exchange,提问作者L.Emil

