1

I am trying to have Button1 change the text on it from 'hi' to 'bye' when it is pressed, and back again when pressed a second time.

Here is my code:

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

I get this error when I press 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
Rory Daulton
  • 21,934
  • 6
  • 42
  • 50
josspgh
  • 31
  • 4

1 Answers1

6

NoneType is the type of the None value. Button1 is set to None.

That's because the .grid() method returns None and that's what you store:

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

Create the button first, then call .grid() separately:

Button1 = Button(
    text="hi", fg="white", bg="purple", width=2, height=1, 
    command=toggletext)
Button1.grid(row=0, column=0)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343