Tkinter 对象没有属性 'bind'

Tkinter Object has no attribute 'bind'

我正在尝试了解 python GUI,但我不知道如何绑定东西。

from tkinter import *
root = Tk()

def leftClick(event):
    print("Left click")

frame = Frame(root,width=300,height=250).pack()
frame.bind("<Button-1>", leftClick)

root.mainloop()

但是...

Traceback (most recent call last):
  File "gui2.py", line 8, in <module>
    frame.bind("<Button-1>", leftClick)
AttributeError: 'NoneType' object has no attribute 'bind'

为了扩展 eyllanesc 的答案,代码应该是

frame = Frame(root,width=300,height=250)
frame.pack()
frame.bind("<Button-1>", leftClick)

一般来说,修改原始对象的方法(如 pack)不会 return 任何东西。您的代码创建了一个 Frame 对象,然后调用 pack 并将输出存储在 frame 中。这相当于写frame = None。您需要先将对象存储为frame,然后再对其进行修改。

此外,如果您有兴趣,Python 中 GUI 的一个很好的开始包是 PySimpleGUI