python-3.x - 为什么 python 编译器在 tkinder 模块中给我一个错误?

标签 python-3.x tkinter compiler-errors

这个问题在这里已经有了答案:





_tkinter.TclError: no display name and no $DISPLAY environment variable

(11 个回答)


2年前关闭。




这是一个示例代码:

from tkinter import * 

root = Tk() 
my_label = Label(root, text="Hello World")
my_laber.pack()
root.mainloop()

这在我的终端上不起作用:Ubuntu(18.04):
 Traceback (most recent call last):
      File "hello_world.py", line 3, in <module>
        root = Tk() #Setting the windown, to do first.
      File "/usr/lib/python3.6/tkinter/__init__.py", line 2023, in __init__
        self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
    _tkinter.TclError: no display name and no $DISPLAY environment variable

我该如何解决?

Python版本
Python 3.6.9 (default, Nov  7 2019, 10:44:02)
[GCC 8.3.0] on linux

最佳答案

您可以通过检查是否为环境变量 DISPLAY 分配了值来解决此问题。如果返回的字符串为空,则分配它:

from tkinter import *
import os

if os.environ.get('DISPLAY', '') == '':
    print('no display found. Using :0')
    os.environ['DISPLAY'] = ':0'

root = Tk()
my_label = Label(root, text="Hello World")
my_label.pack() # watch out here - you have a typo in your code
root.mainloop()

您可以找到更多关于分配给 DISPLAY 的号码的信息。在 this问ubuntu答案。

关于python-3.x - 为什么 python 编译器在 tkinder 模块中给我一个错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60544903/

相关文章:

python - Python3-ModuleNotFoundError : No module named 'numpy'

python - 为什么 Pearson 相关性在 Tensorflow 和 Scipy 之间不同

python - Tkinter 按钮可以有 child 吗?

swift - xcode8 Alamofire 4更新错误 "use of undeclared type Response"

c - OpenMp和代码块16?

java - 捕获 Java 中的转换问题、JLS 的 WRT 协调和实际的 JDK 行为

当我尝试运行文件时 Pythonw 崩溃

python - 权限错误 : [Errno 13] Permission denied: despite granting permission in Dockerfile - what could be the issue?

python - 属性错误 : 'function' object has no attribute 'upper'

Python-属性错误: 'str' object has no attribute 'items'