2

当我尝试运行我的代码(在底部)时,出现以下错误。

AttributeError: 'NoneType' object has no attribute 'config'
Exception in Tkinter callback

苏是这个。此方法适用于配置和 win10toast

L1 = Label(win, text = "Press a button")
L1.grid(row= 0, column= 0, columnspan= 2, padx = 20, pady = 20)

和这个一样。如果不是,有什么区别。据我所知,它们是相同的,只是一个较小并且在一条线上。

L1 = Label(win, text = "Press a button").grid(row= 0, column= 0, columnspan= 2, padx = 20, pady = 20)

主要代码

import datetime as dt
from win10toast import ToastNotifier
from tkinter import *
toast = ToastNotifier()

win = Tk()
win.geometry("200x150")
win.resizable(False, False)
win.configure(background = "Light Blue")
win.title("Demo")
def greeting():
    L1.config(text = "Hello")
    toast.show_toast("Alarm", "You have been summoned", threaded= True)

def farewell():
    L1.config(text = "Goodbye")


L1 = Label(win, text = "Press a button")
L1.grid(row= 0, column= 0, columnspan= 2, padx = 20, pady = 20)
b1 = Button(win, text = "Click Me", width= 7, command=greeting).grid(row= 1, column= 0, padx = 20)
b2 = Button(win, text = "Farewell", width= 7, command=farewell) .grid(row = 1, column= 1, padx = 20)

win.mainloop()
4

1 回答 1

1

tkinter中,如果您以这种方式在窗口中添加小部件:

btn = Button().grid()

.grid()由于方法返回,您失去了对小部件的控制None

正确的方法是:

btn = Button()
btn.grid()

如果您创建自定义类,您可以理解为什么:

class Person:
    def __init__(self, name: str):
        self.name = name

    def get_name(self):
        return self.name


if __name__ == "__main__":
    p = Person(name="Alex")
    print(type(p))

    p = Person(name="Alex").get_name()
    print(type(p))

输出

<class '__main__.Person'>
<class 'str'>
于 2021-06-05T13:28:06.087 回答