Search code examples
pythontkinterrestart

Python: why does first restart works, but second - doesn't?


This is a simple minesweeper game with implementation of windows user interface

The only thing this function has to do is to erase all information (such as text) on the buttons, as well as to create a new random array. It works completely well the 1st time after i press the button, but the second it doesn't work. 2nd time it erases everything (it does its job again as planned), but other functions don't work (I press the buttons after the 2nd restart, and nothing happens, but after the 1st restart everything is fine).

What's going on?? Is it a problem of the memory, where variables are stored, or a specific of the graphical user interface, I am not aware of?

from tkinter import *

def new_game():
    lost = False

    label['text'] = str(mines) + ' mines left'

    global mine_sweep

    mine_sweep = mine_randomization().tolist()
    
    for row in range(10):
        for col in range(10):
            buttons[row][col]['text'] = ''


window = Tk()
window.title('minesweeper')

label = Label(text=str(mines)+' mines left', font=('consolas', 20))
label.pack(side='top')

reset_button = Button(text='restart', command=new_game)
reset_button.pack(side='top')

buttons = buttons.tolist()


frame = Frame(window)
frame.pack()

for row in range(10):
    for col in range(10):
        buttons[row][col] = Button(frame, text='', font=('consolas', 10),
                                   width=2, height=1,
                                   command= lambda row=row, col=col: cell(row, col))
        buttons[row][col].grid(row=row, column=col)

window.mainloop()

(I can't place the whole program here, just part which doesn't work)


here is what the function cell does:

def cell(row, col):

    global lost
    
    if buttons[row][col]['text'] == '' and mine_sweep[row][col] == 0 and not lost:
        open_fields(row, col) 
    elif buttons[row][col]['text'] == '' and mine_sweep[row][col] == 1 and not lost:
        buttons[row][col].config(bg='red', font=('consolas', 10))
        buttons[row][col]['text'] = '*'
        label['text'] = 'You lost!'
        lost = True

    if check_win():
        label['text'] = 'You win!'

Solution

  • Yes, @Matiiss was wright, and the solution was that the variable lost is used in different functions, that's why it should be global. Moreover, when the first game is complete, the lost should again be set to false, in order to start a new game and the computer to know you have actually not yet 'lost'.