更改tkinter中的按钮文本 - 'NoneType'对象不可订阅

时间:2017-01-14 19:24:55

标签: python tkinter

我试图让Button1在按下时将“hi”上的文字改为“bye”,再次按下时再将其改回。

这是我的代码:

from tkinter import *

def toggletext():
  if Button1["text"] == "hi":
    Button1["text"] = "bye"
    Game.update()
  else:
    Button1["text"] = "hi"
    Game.update()

Game = Tk()
Game.wm_title("title")
Button1 = Button(text="hi",fg="white",bg="purple",width=2,height=1,command=toggletext).grid(row=0,column=0)
Button2 = Button(fg="white",bg="purple",width=2,height=1).grid(row=1,column=0)
Button3 = Button(fg="white",bg="purple",width=2,height=1).grid(row=0,column=1)
Button4 = Button(fg="white",bg="purple",width=2,height=1).grid(row=1,column=1)

Game.mainloop()

按下Button1时出现此错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
    return self.func(*args)
  File "C:\Users\User1\Desktop\gridtest2.py", line 4, in toggletext
    if Button1["text"] == "hi":
TypeError: 'NoneType' object is not subscriptable

1 个答案:

答案 0 :(得分:3)

NoneTypeNone值的类型。 Button1设置为None

那是因为.grid()方法返回None,这就是你存储的内容:

Button1 = Button(...).grid(row=0,column=0)

首先创建按钮 ,然后分别调用.grid()

Button1 = Button(
    text="hi", fg="white", bg="purple", width=2, height=1, 
    command=toggletext)
Button1.grid(row=0, column=0)