【问题标题】:'NoneType' object has no attribute '__getitem__' - Tkinter [duplicate]“NoneType”对象没有属性“__getitem__”-Tkinter [重复]
【发布时间】:2016-09-23 03:47:37
【问题描述】:

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

我是 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()

我敢肯定这是一件小事/愚蠢的事情,但仍然感谢您的帮助! :)

【问题讨论】:

  • @AndrewL。是的,你当然是对的,^^ 那是链接到的规范。

标签: python tkinter tk


【解决方案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()

这将正常工作。

【讨论】:

  • 作品完美!谢谢!所以,我所有的问题都是因为我试图同时打包/网格化所有东西。有道理!
  • @DominicFichera 你可以一次性搞定,但如果你之后需要访问、配置或从小部件获取,不行
猜你喜欢
  • 2014-08-14
  • 1970-01-01
  • 2012-12-04
  • 2015-12-17
  • 1970-01-01
  • 1970-01-01
  • 2017-04-19
  • 2018-04-13
相关资源
最近更新 更多