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

jos*_*pgh 1 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()
Run Code Online (Sandbox Code Playgroud)

当我按下 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
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

NoneType是值的类型NoneButton1被设定为None

那是因为该.grid()方法返回None并且这就是您存储的内容:

Button1 = Button(...).grid(row=0,column=0)
Run Code Online (Sandbox Code Playgroud)

创建按钮,然后.grid()单独调用:

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