小编jos*_*pgh的帖子

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

我试图让 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)

python tkinter

1
推荐指数
1
解决办法
2359
查看次数

标签 统计

python ×1

tkinter ×1