Search code examples
pythonfunctiontkinter

Why does my code fail to turn to the second page?


1st i tried working in a program that generates random pokemon so we can create teams to play in showdown. It looked like this

import tkinter as tk
from tkinter import *
import random
import pypokedex

root = tk.Tk() #main

#1ra página
inicio = Frame(root)
inicio.grid(row=0, column=0)
ttl = Label(inicio, text="¿Quienes juegan?")
quienes_juegan = StringVar()
txt1 = Entry(inicio, textvariable = quienes_juegan, width=50) #quienes juegan
btn1 = Button(inicio, text="Confirmar", command= lambda: accion()) #avanza y tira los pokes

#colocando los botones
ttl.grid(padx=650)
txt1.grid(pady=20)
btn1.grid()


elecciones = Frame(root)
elecciones.grid(row=0, column=0)
jugadores = []
def accion(): #pa avanzar de pagina
  quienes_juegan_geteado = quienes_juegan.get()
  variablesss = quienes_juegan_geteado.split()
  jugadores.extend(variablesss)
  print(jugadores)
  elecciones.tkraise()
  botoncitos(elecciones,pokimones)

#Numero de pokimons
numero_pokimons = 30
#Quieres legendarios? si = Tru ; no = False
legendarios = False

#Magia
legendary_list = [144,145,146,150,151,243,244,245,249,250,251,377,378,379,380,381,382,383,384,385,386,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,638,639,640,641,642,643,644,645,646,647,648,649,716,717,718,719,720,721,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809]
pokimones = []
while numero_pokimons != 0:
  poke = random.randint(1,809)
  if poke in pokimones:
    continue
  #iteracion para legendarios
  if legendarios == True:
    if poke in legendary_list :
      pokimones.append(poke)
      numero_pokimons = numero_pokimons-1
    else:
      continue
  #iteracion para no legendarios
  elif legendarios == False:
    if poke in legendary_list:
      continue
    else:
      pokimones.append(poke)
      numero_pokimons = numero_pokimons-1

#ordenamos de mayor a menor los pokimons para que se vea mas bonito
pokimones = sorted(pokimones)
#Imprime los pokimons con su nombre

#'interfaz'
if legendarios == True:
  conf_lege = 'SI'
else:
  conf_lege = 'NO'


elegibles = [pypokedex.get(dex=dex_number) for dex_number in pokimones]
def botoncitos(elecciones, pokimones):
    def crear_boton(index):
        def seleccionar_pokemon():
          button.config(state=DISABLED) 
        button = Button(elecciones, text=item, command=seleccionar_pokemon)
        button.grid(sticky="nsew", row = index // 6, column = index % 6 )

    for index, item in enumerate(elegibles):
        crear_boton(index)

inicio.tkraise()
root.geometry("1400x250")
root.mainloop()

this one worked, it made 30 buttons in rows of 6 with each pokemon generated

I tried to order everything in functions so the code could work when i had to modify some variables, like instead of creating just 30 pokemon numbers, it created 6 per user

import tkinter as tk
from tkinter import *
import random
import pypokedex

root = tk.Tk() #main

jugadores = [] #players
cantidad_jugadores = len(jugadores) #number of players
pokimones = [] #list of pokemon numbers generated by generar_pokimons
elegibles = [pypokedex.get(dex=dex_number) for dex_number in pokimones] #transforms the numbers generated into pokemon names
def accion(): #command that turns to elecciones, the second page
  quienes_juegan_geteado = quienes_juegan.get() #gets the entry
  variablesss = quienes_juegan_geteado.split() #splits the entry
  jugadores.extend(variablesss) #extends it to the players list in the global variable
  print(jugadores) #just to test if it works
  generar_pokimones() #generate the pokemon numbers
  botoncitos(elecciones,pokimones)
  elecciones.tkraise()

def botoncitos(elecciones, pokimones): #creates 1 button per pokemon generated and places them in a grid of 6
    def crear_boton(index):
        def seleccionar_pokemon():
          button.config(state=DISABLED) 
        button = Button(elecciones, text=item, command=seleccionar_pokemon)
        button.grid(sticky="nsew", row = index // 6, column = index % 6 )

    for index, item in enumerate(elegibles):
        crear_boton(index)

def generar_pokimones():
    pokemones= []
    numero_pokimons = cantidad_jugadores * 6 #number of pokemons determined by the number of players
    #if you want to play with legendary pokemons
    legendarios = False
    legendary_list = [144,145,146,150,151,243,244,245,249,250,251,377,378,379,380,381,382,383,384,385,386,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,638,639,640,641,642,643,644,645,646,647,648,649,716,717,718,719,720,721,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809]
    #loop
    while numero_pokimons != 0:
        poke = random.randint(1,809)
        if poke in pokemones:
            continue
        if legendarios == True:
            if poke in legendary_list :
                pokemones.append(poke)
                numero_pokimons = numero_pokimons-1
            else:
                continue
        elif legendarios == False:
            if poke in legendary_list:
                continue
            else:
                pokemones.append(poke)
                numero_pokimons = numero_pokimons-1
    pokemones = sorted(pokemones)#sort
    pokimones.extend(pokemones) #adds the list to the global variable pokimones

#1st page
inicio = Frame(root)
inicio.grid(row=0, column=0)
ttl = Label(inicio, text="¿Quienes juegan?")
quienes_juegan = StringVar()
txt1 = Entry(inicio, textvariable = quienes_juegan, width=50) #who plays?
btn1 = Button(inicio, text="Confirmar", command= lambda: accion()) #turns to the 2nd page, elecciones


ttl.grid(padx=650)
txt1.grid(pady=20)
btn1.grid()

elecciones = Frame(root) #the second page, where it displays 6 buttons with pokemon per user
elecciones.grid(row=0, column=0) 


inicio.tkraise()
root.geometry("1400x250")
root.mainloop()


but now when i run this code and click button 1, it just stops, it seems that it doesnt gets the list of numbers so it can generate the buttons. in accion(), i tried printing the list after its supposed to generate and it comes out blank

apologies for grammar, english its not my first language


Solution

  • Note that cantidad_jugadores is zero because it is set by the line:

    cantidad_jugadores = len(jugadores)
    

    As jugadores is an empty list when the above line is executed.

    So the code block inside the while loop inside generar_pokimones() will not be executed because numero_pokimons (which is calculated from the value of cantidad_jugadores) is zero.

    You need to get the size of jugadores inside generar_pokimones() instead:

    ...
    
    def generar_pokimones():
        pokkemones = []
        numero_pokimons = len(jugadores) * 6   # get the size of jugadores here
        ...
    
    ...
    

    Similar issue on elegibles. You need to create elegibles inside botoncitos() instead:

    def botoncitos(elecciones, pokimones): #creates 1 button per pokemon generated and places them in a grid of 6
        def crear_boton(index):
            def seleccionar_pokemon():
              button.config(state=DISABLED)
            button = Button(elecciones, text=item, command=seleccionar_pokemon)
            button.grid(sticky="nsew", row = index // 6, column = index % 6 )
    
        # create elegibles here
        elegibles = [pypokedex.get(dex=dex_number) for dex_number in pokimones]
        for index, item in enumerate(elegibles):
            crear_boton(index)