【问题标题】:Python tkinter - pack append vs pack separate from root [duplicate]Python tkinter - 包附加与包与根分开[重复]
【发布时间】:2021-12-31 22:28:57
【问题描述】:

我是 python 和 tkinter 的新手。尝试编写一个简单的python代码来获取用户名并打印出来

所以,我尝试了以下

root = Tk() # line 1
e = Entry(root, width = 50).pack() # line 2 option 1 - results in below error as shown below
e = Entry(root, width = 50) # line 2 option 2 - works fine
e.pack() # line 3 option 2 - works fine
def clicking():
    word = "Hello " + e.get()
    myLabel = Label(root,text=word).pack()
myButton = Button(root, text = "Generate", command = clicking).pack()

当我点击Generate 按钮时,我希望看到类似“Hello John”的输出

但是当我编写第 2 行时出现以下错误,如上面第 2 行选项 1 所示

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\test\Anaconda3\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "C:\Users\test~1\AppData\Local\Temp/ipykernel_8876/988003047.py", line 4, in clicking
    word = "Hello " + e.get()
AttributeError: 'NoneType' object has no attribute 'get'

但是,当我将第 2 行写成两个单独的行时,如第 2 行选项 2 和第 3 行选项 2 所示,它工作正常,我得到以下输出。

能否帮助我理解为什么会发生这种情况?用root打包和不用root打包有什么区别?

【问题讨论】:

  • 首先:如果您使用variable = Widget().pack(),那么您将None 分配给变量,因为pack()grid()place() 返回None。这就是问题所在。你应该分两行 variable = Widget()variable.pack()
  • 我无法删除这个问题,因为它已经被回答了。无论如何,可以在这里找到类似的问题 - stackoverflow.com/questions/1101750/…

标签: python tkinter tkinter-canvas tkinter-entry tkinter-layout


【解决方案1】:

当你使用

variable = Widget().pack()

然后您将None 分配给variable,因为pack()grid()place() 返回None

你应该分两行来做

variable = Widget() 
variable.pack()

第一行将小部件分配给variable
在第二行中,您使用 variable 访问此小部件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2012-02-05
    相关资源
    最近更新 更多