Search code examples
pythonpython-3.xtkintertic-tac-toeguizero

Textbox not showing up in my game Tic Tac Toe python


I have made a game called Tic Tac Toe it is a 2 player game and it is when you have etheir get 3 Xs or 3 Os in a row or diagonally.

Code:

from guizero import *

empty = '  '
player = "X"

def clicked(z):
    button = buttonlist[int(z)] # Finds out which button was pressed
    global empty, player
    if button.text != empty:
        pass # If button already pushed do nothing
    else:
        # Marks button with user's go
        button.text = player
        # Switches players
        if player == "X":
            player = "O"
        else:
            player = "X"
    return

app = App(title="Tic Tac Toe", layout="grid", width=200, height=200)
buttonlist = [] # Empty list to contain a list of Buttons

text_box = TextBox(app, text="enter username", align="top")

# Create Buttons for game, in 3 rows of 3
for y in range(3):
    for x in range(3):
        z = (3*y) + x
        buttonlist.append(PushButton(app, text=empty, 
                          args=str(z), grid=[y, x], command=clicked))

app.display()

The problem that I am having is when I put in the line:

text_box = TextBox(app, text="enter username", align="top")

The game still opens up but I get an error saying:

*** GUIZERO WARNING *** [TextBox] object with text "enter username" will not be displayed because it has a missing grid reference.

So could some one please help me fix this.


Solution

  • The doc says you need to pass the grid position when you use a grid layout : https://lawsie.github.io/guizero/layout/#grid-layout

    Here is an example of the parameter you can pass:

    # this will display the textbox after the buttons
    text_box = TextBox(app, text="enter username", align="top",grid=[0,4,3,1])
    #  0 : column position (x)
    #  4 : row position    (y)
    #  3 : span 3 columns  (x span)
    #  1 : span 1 row      (y span)
    

    If you want to display the 2 textbox on top, you can move all positions in the loop :

    text_box = TextBox(app, text="enter username", align="top", grid=[0, 0, 3, 1])
    text_box2 = TextBox(app, text="enter username2", align="top", grid=[0, 1, 3, 1])
    
    z=0
    for x in range(3):
        for y in range(2, 5):
            buttonlist.append(PushButton(app, text=empty, args=str(z), grid=[x, y], command=clicked))
            z+=1
    
    app.display()