Python TypeError: 'NoneType' 对象不支持项目分配?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4975010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:24:50  来源:igfitidea点击:

TypeError: 'NoneType' object does not support item assignment?

pythontkinter

提问by Kosig

So I start a root screen with a "file select" and a "go" button. The go button is disabled and I want to make it active after the file has been selected. When I select the file go should become active but instead this error "TypeError: 'NoneType' object does not support item assignment" Here is some sample code

所以我用一个“文件选择”和一个“开始”按钮启动一个根屏幕。转到按钮已禁用,我想在选择文件后将其激活。当我选择文件时,go 应该变为活动状态,而是出现此错误“TypeError: 'NoneType' object does not support item assignment” 这是一些示例代码

import Tkinter
import tkFileDialog

def chooseDir():
    dir1=tkFileDialog.askopenfilename(parent=root, title='choose file path')
    go['state']=Tkinter.ACTIVE
root=Tkinter.Tk()
global go
go=Tkinter.Button(text='file location',command=chooseDir,state=Tkinter.DISABLED).pack()
root.mainloop()

采纳答案by Keith

This line:

这一行:

go=Tkinter.Button(text='file location',command=chooseDir,state=Tkinter.DISABLED).pack()

is creating a temporary object, then calling pack() on it. The pack method returns None, so gois assigned None.

正在创建一个临时对象,然后对其调用 pack()。pack 方法返回 None,因此go被分配了 None。

Remove the .pack() then gowill be the Button object. Then call go.pack().

删除 .pack() 然后go将是 Button 对象。然后调用go.pack()

回答by Daniel DiPaolo

(update for new error) godoesn't exist in that scope, you'll need to get access to it somehow, or by using the one in the global scope using global goinside the chooseDirmethod perhaps

(更新新错误) go在该范围内不存在,您需要以某种方式访问​​它,或者通过global gochooseDir方法内部使用全局范围中的那个

Tkinter.Buttons don't behave like dictionaries, you can change their status via the config()method.

Tkinter.Buttons 的行为不像字典,您可以通过config()方法更改它们的状态。

Try:

尝试:

go.config(state=Tkinter.ACTIVE)