Home > Software engineering >  How can I make it so the Tkinter button can only be pressed once?
How can I make it so the Tkinter button can only be pressed once?

Time:04-22

I have this code where I am trying to have it so I can only press the button once and then it becomes disabled, but I keep getting the error TypeError: 'NoneType' object is not subscriptable, I'm not so sure what I am doing incorrect. Any help is appreciated. Here is my code:

import tkinter as tk
from tkinter import *
from tkinter import ttk

team_array = []
team_dict = {}

def score_event1_team():
    global team_array
    global team_dict

    #First Event, 1st Team, Adding 15 points.
    event1T = str(input("What team was first place?"))
    
    #ADDING 15 POINTS TO FIRST TEAM IN THE DICTIONARY WITH GET METHOD.
    team_dict[event1T] = team_dict.get(event1T, 0)   15
    print(team_dict)
    print(f"Team {event1T} has been added 15 points.")

    if (button_event_1['state'] == NORMAL):
        button_event_1['state'] = DISABLED


root = Tk()
root.title("Sports Event Organiser!")
root.geometry("600x500")

button_event_1 = Button(root,
    text="Event Pending",
    bg="white",
    height = 1,
    command=(score_event1_team),
    state = NORMAL,
).pack(pady = 10)


root.mainloop()

CodePudding user response:

The problem is in your following code segment, where you are creating a button

button_event_1 = Button(root,
    text="Event Pending",
    bg="white",
    height = 1,
    command=(score_event1_team),
    state = NORMAL,
).pack(pady = 10)

You are calling pack(pady = 10) immediately on the button due to which your button_event_1 object is not referring to the button but None returned by pack()

the solution is simple, remove it from there and then pack the button separately, after button initialization

button_event_1 = Button(root,
    text="Event Pending",
    bg="white",
    height = 1,
    command=(score_event1_team),
    state = NORMAL,
)

button_event_1.pack()

CodePudding user response:

The thing you are doing wrong is this line button_event_1 = Button(....).pack() as you are packing it with the button and pack returns a nontype object you need to do button_event_1 = Button(....) and than button_event_1.pack() both in separate lines. The pack function returns a none type object and in your question thus button_event_1 is None

  • Related