为什么在Python 3.6.7中出现错误“ NoneType”对象没有属性“ set”的错误?

时间:2019-08-02 16:46:54

标签: python tkinter runtime-error ttk

我正在清理一些原始代码,

program_lbl = Label(input_frame, text="Program")
program_lbl.grid(column=1, row=0)
program_combo = Combobox(input_frame, values = ['program1', 'program2'], state = "readonly", width = 8)
program_combo.grid(column=1, row=1)
program_combo.set('program1') #set program1 as default

我将其压缩为:

program_lbl = Label(input_frame, text="Program").grid(column=1, row=0)
program_combo = Combobox(input_frame, values = ['program1', 'program2'], state = "readonly", width = 8).grid(column=1, row=1)
program_combo.set('HUNTER') #set program1 as default

但出现以下错误:

Traceback (most recent call last):
  File "c:\Users\j56967\.vscode\extensions\ms-python.python-2019.3.6558\pythonFiles\ptvsd_launcher.py", line 45, in <module>
    main(ptvsdArgs)
  File "c:\Users\j56967\.vscode\extensions\ms-python.python-2019.3.6558\pythonFiles\lib\python\ptvsd\__main__.py", line 391, in main
    run()
  File "c:\Users\j56967\.vscode\extensions\ms-python.python-2019.3.6558\pythonFiles\lib\python\ptvsd\__main__.py", line 272, in run_file
    runpy.run_path(target, run_name='__main__')
  File "C:\Python367-64\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Python367-64\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Python367-64\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "c:\Users\j56967\Documents\python\gui_refinement.py", line 46, in <module>
    program_combo.set('program1')
AttributeError: 'NoneType' object has no attribute 'set'

当我在program_combo.set('program1')行中注释掉时,一切正常,但是组合框没有默认选择。

编辑:下面标记的重复项很好地回答了我的问题,谢谢。

1 个答案:

答案 0 :(得分:0)

program_lbl = Label(input_frame, text="Program")
program_lbl.grid(column=1, row=0)

在这里,您正在创建标签,然后在其上调用grid()

program_lbl = Label(input_frame, text="Program").grid(column=1, row=0)

在这里,您正在从Label(...).grid(...)创建一个对象,该对象什么也不返回。