我想测试一个按钮的代码。然而,它只是给了我一个结果:显示是不能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()发布于 2020-04-17 10:45:13
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实际上,您需要的是为新创建的mainloop对象调用Root。在__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__(),这将在实例化NameError时引发Root。使用父类初始化对象的正确语法是
super(Root, self).__init__()或者简单地说,使用现代语法
super().__init__()https://stackoverflow.com/questions/61269314
复制相似问题