NiceGui - Accessing buttons in grid from outside of function

27 views Asked by At

First of all I have to say that I am new to python and NiceGUI. I have trouble accessing buttons in grid.

I am trying call buttons from outside of function where I created them. (Specifically disable/enable them.)

For context I am creating Pairs game.

Here is code in my frontend file:

There is another file game_logic.py which gives me only logic to the Pairs game. Creating chars etc.. In frontend I need it only for change_button().

What I am trying to accomplish is that I am going to be able to call disable_buttons() outside of game() function. Basically to work with all buttons, not only one button when someone presses that button.

I tried multiple solutions like putting "global" in front of buttons, tried creating list of buttons outside of game function but no luck. If I called function game() then it will fill the list, but problem is that I think those buttons are different from the real one on the website since I didn't need to call game() function.. When I click "Start game" it will automatically show game() screen

from nicegui import ui
from game_logic import *

buttons = []

def disable_buttons():
    for i in range(36):
        buttons[i].disable()

@ui.page('/game', dark=True)
def game():
    with ui.element('div').classes('flex column items-center absolute-center'):
        ui.label('Player 1 - Player 2').classes('text-h2').style('margin-bottom: 20px;')
        with ui.grid(columns=6,rows=6).classes('justify-center'):
            for i in range(36):
                btn = ui.button(text='X', color='grey-9', on_click=lambda e, i=i: change_button(e, i)).classes('text-h4').style("width: 100px; height: 100px")
                buttons.append(btn)
                #**disable_buttons()**
#**disable_buttons()**

with ui.column().classes('absolute-center items-center'):
    ui.label("Pairs Game").classes('text-h1')
    ui.button(
        text='START GAME',
        color='red',
        on_click=lambda: ui.navigate.to('/game')
    ).classes('text-h5')

ui.run(title="Pair Game", dark='True', port=80)

Screenshot - Grid of buttons

0

There are 0 answers