' NoneType'对象没有属性' __ getitem __' - Tkinter

时间:2016-09-23 03:47:38

标签: python tkinter tk

我已经查看了现有的问题,但到目前为止我还没有找到解决方案。

我是Python编程语言的新手并且已经开始使用Tk,但在尝试“获取”时仍会收到以下错误消息:一个值(来自复选框)或更改标签的值:

' NoneType'对象没有属性' getitem '

以下是我的代码示例,其中单击按钮时收到错误

from Tkinter import *

the_window = Tk()

the_window.title('Button Change Colour')

def change_to_red():
    colour_area['text']='Red'

colour_area = Label(the_window, bg='Grey', text = 'test', width = 40, height = 5).grid(row = 1, column = 1, padx = 5, pady = 5)
red_button = Button(the_window, text='Red', width = 5, command = change_to_red).grid(row = 2, column = 1)

the_window.mainloop()

我确定它有点小/傻,但还是会感激你的帮助! :)

1 个答案:

答案 0 :(得分:1)

听起来令人困惑,但您没有将colour_area声明为标签,只是将其添加到网格中。
这是你的错误:

from Tkinter import *

the_window = Tk()

the_window.title('Button Change Colour')

def change_to_red():
    colour_area['text']='Red'

# initializing colour_area as a Tk.Label
colour_area = Label(the_window, bg='Grey', text = 'test', width = 40, height = 5)
# adding it to the grid
colour_area.grid(row = 1, column = 1, padx = 5, pady = 5)
red_button = Button(the_window, text='Red', width = 5, command = change_to_red).grid(row = 2, column = 1)

the_window.mainloop()

这将正常工作。