由于错误,使用tkinter的python程序无法运行

2024-10-01 00:20:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试学习如何使用tkinter创建GUI。conde非常基本,但我遇到以下错误:

Exception has occurred: TclError
no display name and no $DISPLAY environment variable
  File "/home/josh/Documents/VSC/python/SECOM/mainWindow.py", line 7, in __init__
    self.wind = Tk()
  File "/home/josh/Documents/VSC/python/SECOM/mainWindow.py", line 12, in <module>
    MW = mainWindow()

当我用谷歌搜索这种错误时,只有raspberry pi或远程服务器之类的东西才有答案。我只是在使用ubuntu(20.04)和带有python(3.8)的conda(4.8.3)venv。我也在使用VSC,并将venv作为VSC中的解释器。帮助:c

MainWindow.py

from tkinter import ttk
from tkinter import *

class mainWindow:
    def __init__(self):
        self.title = "SECOM"
        self.wind = Tk()
        self.wind.title(self.title)


if __name__ == '__main__':
    MW = mainWindow()
    window.mainloop()

Tags: nonamepyselfhometitletkinter错误
1条回答
网友
1楼 · 发布于 2024-10-01 00:20:40

您在代码中谈论了很多关于windows,但实际上没有多少是window。有些根本算不上什么。试试这个

import tkinter as tk


class Root(tk.Tk):
    def __init__(self, **kwargs):
        tk.Tk.__init__(self, **kwargs)

        #PUT YOUR APP HERE


if __name__ == '__main__':
    root = Root()
    root.title("SECOM")
    root.mainloop()

以下是您的脚本的问题

from tkinter import ttk
#importing like this pollutes your namespace
from tkinter import *

class mainWindow:
    def __init__(self):
        #there is no reason to store a reference to the title
        self.title = "SECOM"
        #why are you burying your root in a class property
        self.wind = Tk()
        #this is why you don't need a reference to title
        self.wind.title(self.title)


if __name__ == '__main__':
    #sure
    MW = mainWindow()
    #window? window where? You buried this in MW.wind
    window.mainloop()

相关问题 更多 >