为什么我得到了"Display is not capable of DPMS"?

Why did I get "Display is not capable of DPMS"?

我想测试一个按钮的代码。然而它只是给了我结果:显示器不支持 DPMS。为什么?

from tkinter import *
# tkinter

class Root(Tk):
  def __init__(self):
  # define self
    super(Root, self),__init__()
    self.title("Tkinter Button")
    # title of new window
    self.minsize(640,400)
    # size of button
    self.wm_iconbitmap('icon.ico')




    button = Button(self, text = "Click Me")
    # text on the button
    button.grid(column = 0, row = 0)
    # location in the new window opened

    root = Root()
    root.mainloop()

Display is not capable of DPMS 不是错误,它只是一个警告,您的代码无论如何都会起作用。您的实际问题是您 mainloop 没有正确 tk.Root.

您可能陷入了无限递归,因为您正在 Root 对象的初始化中初始化一个 Root 对象。

class Root(Tk):
    def __init__(self):
        super().__init__()

        # you are initializing another Root object here!
        root = Root()  
        # that will itself initialize another Root object,
        # and that will itself initialize another Root object, etc.

        root.mainloop()  # this statement will never be reached

您真正想要的是为新创建的 Root 对象调用 mainloop。在__init__方法中,这个新创建的对象就是self。此代码应按预期工作。

class Root(Tk):
    def __init__(self):
        super().__init__()

        self.title("Tkinter Button")
        self.minsize(640,400)
        self.wm_iconbitmap('icon.ico')

        button = Button(self, text = "Click Me")
        button.grid(column = 0, row = 0)

        self.mainloop()

也从对象本身的外部简单地考虑 运行 mainloop,在 Tkinter 的对象初始化本身中通常不希望这样做

# remove self.mainloop() from Root.__init__ first
root = Root()
root.mainloop()  # better


旁注:你用逗号而不是点写 super(Root, self),__init__(),在实例化 Root 时应该引发 NameError。用父 class 初始化对象的正确语法是

super(Root, self).__init__()

或者简单地说,using modern syntax

super().__init__()