【问题标题】:$DISPLAY environment problem with Tkinter in VScodeVScode 中 Tkinter 的 $DISPLAY 环境问题
【发布时间】:2020-12-26 04:01:10
【问题描述】:

我正在尝试使用 tkinter 构建一个简单的倒数计时器,但是当我运行代码时会出现以下消息:

File "/home/user/Desktop/Beginner Projects/Pythons/countdown timer.py", line 20, in <module>
    root = Tk()
  File "/usr/lib/python3.8/tkinter/__init__.py", line 2261, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

我搜索了很多答案,但大部分都没有理解。我该如何解决这个问题并让 tkinter 在 VScode 上工作?提前致谢!

编辑 1:

from tkinter import *
from tkinter import ttk
from tkinter import font
import time
import datetime

global endTime

def quit(*args):
    root.destroy()

def cant_wait():
    timeLeft = endTime - datetime.datetime.now()
    timeLeft = timeLeft - datetime.timedelta(microseconds=timeLeft.microseconds)

    txt.set(timeLeft)

    root.after(1000, cant_wait)

root = Tk()
root.attributes("-fullscreen",False)
root.configure(background="black")
root.bind("x", quit)
root.after(1000, cant_wait)

endTime = datetime.datetime(2020,6,7,8,0,0)

fnt = font.Font(family="Helvetica", size=90, weight="bold")
txt = StringVar()
lbl = ttk.Label(root, textvariable=txt, font=fnt, foreground="white", background="black")
lbl.place(relx = 0.5, rely = 0.5, anchor="center")

root.mainloop()

【问题讨论】:

  • 我认为这通常是因为它无法在屏幕上显示 GUI,但我不知道为什么 VS 代码会发生这种情况,我使用 VS 代码并且很好。
  • 请发布您的代码。我需要你的代码来检查它。
  • 代码在我的系统上运行良好

标签: python tkinter visual-studio-code display


【解决方案1】:

我在使用 PySimpleGUI 的 Ubuntu 20.04.1 上遇到了同样的问题。

如果在尝试通过单击右上角的绿色箭头(对应于“在终端中运行 Python 文件”)运行脚本时出现问题,一种解决方案是进入 Terminal 并设置适当地显示变量。
就我而言,以下命令起到了作用: export DISPLAY=:1 DISPLAY 变量的实际值取决于环境的具体情况(参见例如 [https://unix.stackexchange.com/a/612453]

如果在按 F5(调试)或 Ctrl+F5(不调试运行)时出现问题,则需要编辑 launch.json 文件。 可以通过 Run->Open Configurations 菜单访问该文件。 (这假设已经选择了 Debugging/Running 的配置。) 我们需要指示 VSCode 设置 DISPLAY 环境变量。为此,请在相应部分添加行 "env": {"DISPLAY": ":1"},。 就我而言,该部分是以"name": "Python: Current File", 开头的部分。

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 2021-05-01
    • 2017-06-16
    • 2019-12-15
    • 1970-01-01
    • 2020-07-20
    • 2015-05-26
    • 2017-02-17
    相关资源
    最近更新 更多