KIRA
KIRA

Reputation: 49

How to avoid resetting a value by pressing a button again

The buttonGuess runs numRandom function when it's pressed and it also runs remainingAttemps function. The problem is if user presses the buttonGues, Attemps value is reasigned again.

import tkinter
import random

window = tkinter.Tk()
window.geometry('600x500')

x = random.randint(1,10)
remainingTime = True
Attempts = 4

def countdown (time_left):
    global remainingTime
    if remainingTime == True:
        lblCrono.configure(text = str(time_left))
        if time_left > 0:
            time_left = time_left - 1
            window.after(1000, countdown, time_left)
        else:
            remainingTime = False
            lblCrono.configure(text = 0)
            return remainingTime, gameOver()
    else:
        return

def numRamdom():
    global Attempts
    numWritten = int(entryWriteNumber.get())
    if numWritten > x:
        lblClue.configure(text = 'Its a smaller number')
        return remainingAttempts(Attempts)
    if numWritten < x:
        lblClue.configure(text = 'Its a bigger number')
        return remainingAttempts(Attempts)
    if numWritten == x:
        lblClue.configure(text = 'Congratulations ;)')
        remainingTime = False
        return remainingTime, countdown(0)

def gameOver():
    if remainingTime == False and Attempts != 0:
        lblClue.configure(text = '¡Time\'s up!')
    else:
        lblClue.configure(text = 'No attempts')

def remainingAttempts(countAtempts):
    Attempts = countAtempts
    if Attempts == 0:
        return remainingTime, countdown(0), Attempts, gameOver()
    else:
        Attempts = Attempts - 1

entryWriteNumber = tkinter.Entry(window)
entryWriteNumber.grid(column = 0, row = 1, padx = 10, pady = 10)

lblNumber = tkinter.Label(window, text = 'Number', font = 'Comic 13 bold')
lblNumber.grid(column = 0, row = 0, padx = 10, pady = 10, sticky = tkinter.W )

buttonGuess = tkinter.Button(window, text = 'Guess', bg = 'light grey', padx = 20, command = numRamdom)
buttonGuess.grid(column = 0, row = 2, sticky = tkinter.W, padx = 10, pady = 10)

lblClue = tkinter.Label(window, text = 'Clue', font = 'Comic 13 bold')
lblClue.grid(column = 0, row = 3, padx = 10, pady = 10, sticky = tkinter.W )

lblCrono = tkinter.Label(window, text = '', bg = 'white', fg = 'red', font = 'Comic 20', padx = 50, pady = 5)
lblCrono.grid(column = 1, row = 5, sticky = tkinter.S, padx = 100, pady = 150)


countdown(30)


window.mainloop()

Upvotes: 2

Views: 76

Answers (1)

OysterShucker
OysterShucker

Reputation: 5531

It's all much easier to manage when you get rid of everything that either isn't doing anything or is unnecessary. All your returns are doing nothing. Creating a remainingTime variable when you have a counter is unnecessary. Giving your widgets and functions a bunch of complicated and/or misleading names, isn't helping. You were calling countdown(0) which calls gameOver() and then calling gameOver().

You never put something on row=4, but you put your timer on row=5. This is visibly no different than putting it on 4. You had very repetitive grid options so I homogenized them in a dict and used that dict as **kwargs. Writing your arguments like this -> func(arg1 = value1, arg2 = value2, ...) has no benefit. There's no reason to keep a reference to lblNumber or buttonGuess. You never modify or further reference either, in any way. If you don't specify a column, tkinter will assume you mean column=0. If you don't specify a row, tkinter will assume you mean 1 row greater than the total current rows, regardless of column. Importing tkinter without an alias just gives you more to type.

Below is my edit of your game based on everything I just wrote.

import tkinter as tk
import random

root = tk.Tk()
root.geometry('600x500')

x = random.randint(1,10)
remaining = 4

def countdown(time_left):
    global process
    chrono['text'] = str(time_left)
    if time_left:
        process = root.after(1000, countdown, time_left-1)
    else:
        gameOver()

def check():
    global remaining
    
    n = int(guess.get())
    if n == x:
        gameOver(True)
        return
    else:
        clue['text'] = f'Its a {"smaller" if n > x else "bigger"} number'
        
    remaining -= 1
    if not remaining:
        gameOver()

def gameOver(win=False):
    root.after_cancel(process)
    if not win:
        clue['text'] = '¡Time\'s up!' if remaining else 'No attempts remain'
    else:
        clue['text'] = 'Congratulations ;)'


grid = dict(padx=10, pady=10, sticky=tk.W)

tk.Label(root, text='Number', font='Comic 13 bold').grid(**grid)

guess = tk.Entry(root)
guess.grid(**grid)

tk.Button(root, text='Guess', bg='light grey', padx=20, command=check).grid(**grid)

clue = tk.Label(root, text='Clue', font='Comic 13 bold', width=20, anchor='w')
clue.grid(**grid)

chrono = tk.Label(root, text='', bg='white', fg='red', font='Comic 20', padx=50, pady=5)
chrono.grid(column=1, **grid)

countdown(30)

root.mainloop()

Upvotes: 1

Related Questions