0

I got my motivation from this post: Incerasing number by every second +1 in Tkinter label

So I decided to make a Scoreboard with Tkinter and I am about to pull my hair out because I know its a basic question with a most likely obvious answer, I just cant figure it out.

Its a football scoreboard. Comprised of 4 buttons

score_dict = {"Touchdown": 6, "Extra Point": 1, 'Field Goal': 3, "Conversion": 2, "Safety": 2}

Every time I hit the button I want the label to reflect the score but I cant figure out how to keep the previous amount of the label and add on to it.

So if the label reads 6 and I add a field goal it should read 10 instead of starting over again.

    # Creating label + buttons and putting them on screen
label = Label(root, text=0)
buttons = [Button(root, text=i, command=lambda i=i: press(i)) for i in score_dict.keys()]

for i in range(len(buttons)):
    buttons[i].grid(row=1, column=i)

label.grid(row=0, column=2)

# press function from button list comprehension:
def press(i):
    global label
    if score_dict[i] == 6:
        if label['text'] < score_dict[i]:
            label['text'] += 1
            root.after(100, press, i)
    if score_dict[i] == 1:
        if label['text'] < score_dict[i]:
            label['text'] += 1
            root.after(100, press, i)
    if score_dict[i] == 3:
        if label['text'] < score_dict[i]:
            label['text'] += 1
            root.after(100, press, i)
    if score_dict[i] == 2:
        if label['text'] < score_dict[i]:
            label['text'] += 1
            root.after(100, press, i)

The problem is the if statement. When I press the button once, just as long as the score is more than the label reads it doesn't fit any of the conditions but I'm not sure how else to phrase it.

I posted this all over Reddit for 5 days with no answers and I'm ready to give up on it.

  • You can assign a variable as the initial score and update that variable in the function. Use the variable as the text for the label. – IJ_123 Oct 14 '21 at 05:43
  • After much fiddling I think I have an answer that seems to work. – Derek Oct 14 '21 at 07:06

1 Answers1

0

I've made necessary changes to function press. Code requires a working dictionary to keep track of score and a static dictionary to reset the testing statement.

Total score is in label.

import tkinter as tk

score_dict = {"Touchdown": 6, "Extra Point": 1,
              "Field Goal": 3, "Conversion": 2,
              "Safety": 2}
working_dict = score_dict.copy()

root = tk.Tk()

label = tk.Label(root, text = 0)
label.grid(sticky = tk.NSEW)

def press(i):
    if working_dict[i] > 0:
        working_dict[i] -= 1
        label['text'] += 1
        root.after(100, press, i)
    else:
        working_dict[i] = score_dict[i]

buttons = [tk.Button(root, text = i, command = lambda i = i: press(i)) for i in score_dict.keys()]

for i in range(len(buttons)):
    buttons[i].grid(row = 1, column = i)

root.mainloop()
Derek
  • 1,916
  • 2
  • 5
  • 15