【问题标题】:Tkinter Object has no attribute 'bind' [duplicate]Tkinter 对象没有属性“绑定”[重复]
【发布时间】:2019-08-22 03:42:17
【问题描述】:

我正在尝试学习 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'

【问题讨论】:

  • frame = Frame(root,width=300,height=250).pack()更改为frame = Frame(root,width=300,height=250)并添加frame.pack()
  • @eyllanesc 是正确的,pack() 返回None

标签: python tkinter python-3.7


【解决方案1】:

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

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

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

另外,如果您有兴趣,可以从PySimpleGUI 开始使用 Python 中的 GUI。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多